SQL/C# - Best method for executing a query

前端 未结 5 555
谎友^
谎友^ 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:25

    It depends. If you don't care about the result of the query forking a process which uses sqlcmd might be OK. If on the other hand you need to control the results it would be better to use ADO.NET. To avoid keeping the connection open for a long time make sure you disable ADO.NET connection pooling by adding Pooling=false to your connection string:

    using (var conn = new SqlConnection("Data Source=server;Initial Catalog=somedb;User Id=foo;Password=secret;Pooling=false"))
    using (var cmd = conn.CreateCommand())
    {
        conn.Open();
        cmd.CommandText = "DELETE FROM foo";
        var result = cmd.ExecuteNonQuery();
    }
    

提交回复
热议问题