c# - 为什么必须为非查询打开连接而不是填充数据集?

标签 c# sql windows database-connection

当我连接到我的 C# 应用程序中的 SQL 数据源时,我可以使用以下代码填充数据集。请注意,我没有明确打开与数据源的连接。

SqlConnection cw_con = new SqlConnection("Server=Server;Database=Database;User=User;password=password");
SqlCommand cmd = new SqlCommand("SELECT * FROM Example WHERE value = value");
cmd.Connection = cw_con;

//Create DataSet
DataSet cw_ds = new DataSet("cw_ds");
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
//Execute Command and Fill DataSet
da.Fill(cw_ds);
cw_ds.Clear();

但是,如果我想执行非查询,例如 INSERT INTOUPDATE,为什么我必须使用 connection.Open 显式打开连接();?

SqlConnection cw_con = new SqlConnection("Server=Server;Database=Database;User=User;password=password");
cw_con.Open();
SqlCommand cmd = new SqlCommand("UPDATE example SET value = value WHERE value = value");
cmd.Connection = cw_con;
cmd.ExecuteNonQuery();
cw_con.Close();

最佳答案

那是因为 DataAdapter 在最初关闭时隐式打开连接。如果之前已关闭,它将在之后关闭它,否则连接将保持打开状态。

来自 MSDN :

The Fill method retrieves the data from the data source using a SELECT statement. The IDbConnection object associated with the select command must be valid, but it does not need to be open. If the IDbConnection is closed before Fill is called, it is opened to retrieve data and then closed. If the connection is open before Fill is called, it remains open.

当使用 SqlCommand 时,您必须自己明确地打开和关闭连接。

作为旁注:

  1. 使用parameters避免 SQL 注入(inject)
  2. 使用using-statement对于任何实现 IDisposable 的东西,尤其是 Connections,因为它确保它尽快被处理/关闭,即使在出现错误的情况下也是如此

关于c# - 为什么必须为非查询打开连接而不是填充数据集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10620592/

相关文章:

sql - 哪种 SQL 更新更快/更高效

windows - Windows 上的 Hadoop - "Error JAVA_HOME is incorrectly set."

c# - 使用 C# 编程 EV3

C# 图表轴标签格式不正确

sql - MYSQL 选择修剪

sql - 我有一个奇怪的错误

c++ - 动态链接如何对对象的变化使用react

windows - 什么时候无法支持 Visual Basic 6.0 应用程序?

c# - 如何使用 LibGit2Sharp 获取分支?

c# - 如何基于自定义属性添加一对多关系