我正在尝试学习如何在 C# 中使用数据库,当我必须使用 DataSet 、 SqlDataAdapter 和 SqlCommandBuilder 时,我已经进入了教程的一部分。这是我在教程示例中编写的代码:
public void InitData() {
//instantiate the connection
conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=\"D:\\Projects IDE\\Visual Studio\\Exercitii\\Console.app\\WindowsFormsApplication1\\WindowsFormsApplication1\\PlanetWrox.mdf\";Integrated Security=True;User Instance=True");
//1.instantiate a new DataSet
dsCustomers = new DataSet();
//2.init SqlDataAdapter with select command and connection
daCustomers = new SqlDataAdapter("SELECT Id ,Name, SortOrder FROM Genre", conn);
// 3. fill in insert, update, and delete commands
SqlCommandBuilder cmdBldr = new SqlCommandBuilder(daCustomers);
// 4. fill the dataset
daCustomers.Fill(dsCustomers, tableName);
}
public void btnUpdateClicked(object sender, EventArgs e) {
// write changes back to DataBase
daCustomers.Update(dsCustomers, tableName);
}
这里有几件事我不明白:
我注意到的第一件事是我不必打开和关闭数据库。根据我对数据库的有限知识,我知道为了访问数据你必须打开一个连接,然后你你必须关闭它。这一定发生在幕后的某个地方。是吗?如果那是女巫的方法,那该怎么做?
第二个问题是关于 SqlDataAdapter 和 SqlCommandBuilder。我不明白 SqlCommandBuilder 在这里做什么。SqlDataAdapter 不是执行 sql 查询的那个吗?
请您参考如下方法:
The first thing I noticed is that I do not have to open and close the database.
SqldataAdapter.Fill将为您打开/关闭连接。
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.
SqlCommandBuilder从您提供的选择语句的元数据生成 INSERT、UPDATE 或 DELETE 语句。通过这种方式您可以调用daCustomers.Update并且对 DataSet 所做的所有更改都将自动更新到数据库中。
