SQL/C# - Best method for executing a query

前端 未结 5 546
谎友^
谎友^ 2020-12-02 01:49

I need to execute a sql query from within a c# class. I have thought of 2 options

  1. Starting a process of sqlcmd.
  2. Using a SqlCommand object.
5条回答
  •  清歌不尽
    2020-12-02 02:08

    Use a SqlCommand. This code will only keep the connection alive for a very short period of time (as long as your query is performant):

    DataTable results = new DataTable();
    
    using(SqlConnection conn = new SqlConnection(connString))
        using(SqlCommand command = new SqlCommand(query, conn))
            using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
               dataAdapter.Fill(results);
    

提交回复
热议问题