- 31
- 1月
今天看到了《C#入门经典》的第24章“数据库和ADO.NET”,由于上学期听过大四的那门.net数据库编程,所以看这部门感觉是颇顺利的,要做的基本上就是逐一验证书上的代码。
不 过刚刚发现一个课上老师没提到过的类:SqlCommandBuilder,而且代码中也有使用,赶紧研究了一下,发现确实是个好东西。有了它在使用 DataAdapter时就不用自己写与SELECT语句对应的那些INSERT、UPDATE、DELETE语句了。只要在声明好一个 DataAdapter对象后,用这个DataAdapter初始化一个SqlCommandBuilder对象就OK,adapter就可以直接 Update()了。
例:
SqlConnection thisConnection = new SqlConnection(@”Data Source=riqe\sqlexpress;Initial Catalog=Northwind;Integrated Security=True”);
SqlDataAdapter thisAdapter = new SqlDataAdapter(“SELECT CustomerID,CompanyName FROM customers”, thisConnection);
SqlCommandBuilder thisBuilder = new SqlCommandBuilder(thisAdapter);
DataSet thisDataSet = new DataSet();
thisAdapter.Fill(thisDataSet, “Customers”);
thisDataSet.Tables["Customers"].Rows[9][1] = “Acme, Inc.”;
thisAdapter.Update(thisDataSet, “Customers”);
thisConnection.Close();
如果没有定义那个SqlCommandBuilder的话,可是要自己设定DataAdapter的UpdateCommand属性,可是很麻烦的。