2010-09-17 28 views
17

我需要从c#类中执行sql查询。我想到了2个选项SQL/C# - 执行查询的最佳方法

  1. 启动一个sqlcmd进程。
  2. 使用SqlCommand对象。

我的问题是哪个会更好?解决方案只在短时间内连接到服务器很重要。

如果上述情况不好,我愿意接受其他观点。

在此先感谢。

+0

您是否期望将记录集返回给您的应用程序以供使用,或者您只是试图运行查询并继续前进? – AndHeCodedIt 2010-09-17 13:08:41

+0

你想专门避免连接池,还是只是试图遵循最佳实践? – RedFilter 2010-09-17 13:18:17

+0

对不起,不清楚。没有查询是插入,结果是不需要的。 – 2010-09-17 13:18:51

回答

28

使用SqlCommand。此代码将仅保持连接存活时间很短的时间(只要你的查询是高性能):

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); 
+0

这取决于它是否会保持连接在短时间内存活。如果你不小心,它可能会保持连接,甚至没有一个单一的连接,但其中许多连接打开整个应用程序的生命周期。详情请参阅我的回答。 – 2010-09-17 13:14:46

+0

如何用我的代码实现:http:// stackoverflow。com/questions/23617661/why-the-sql-command-is-executed – SearchForKnowledge 2014-05-12 19:56:09

0

我觉得SqlCommand的是一个明显的赢家,因为你不需要线了不同处理。完成之后,您可以立即关闭数据库连接。

然后,您还可以将应用程序分发到没有sqlcmd可用的计算机。

3

这取决于。如果您不关心查询分叉的结果,那么使用sqlcmd的进程可能没问题。另一方面,如果您需要控制结果,则最好使用ADO.NET。为了避免加入Pooling=false到连接字符串保持连接打开很长一段时间确保您禁用ADO.NET connection pooling

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(); 
} 
+0

Nitpick:据我所知,Windows没有进程分叉。 – 2017-09-12 12:52:22

7

MSDN:

下面的示例创建一个SqlConnection,一个SqlCommand和SqlDataReader对象。该示例读取数据,并将其写入控制台。最后,该示例在退出Using代码块时关闭SqlDataReader,然后关闭SqlConnection。

private static void ReadOrderData(string connectionString) 
{ 
    string queryString = 
     "SELECT OrderID, CustomerID FROM dbo.Orders;"; 
    using (SqlConnection connection = new SqlConnection(
       connectionString)) 
    { 
     SqlCommand command = new SqlCommand(
      queryString, connection); 
     connection.Open(); 
     SqlDataReader reader = command.ExecuteReader(); 
     try 
     { 
      while (reader.Read()) 
      { 
       Console.WriteLine(String.Format("{0}, {1}", 
        reader[0], reader[1])); 
      } 
     } 
     finally 
     { 
      // Always call Close when done reading. 
      reader.Close(); 
     } 
    } 
} 
0

我认为SqlCommand是个好主意,但请记住,只有在连接到SQL Server时才能使用此类。如果您正在处理Oracle或与其他数据库的OleDb连接,则需要其他类型的Command/Connection类。所有的数据命令对象都继承自DbCommand,所以我会对此进行阅读。