ADO.NET:从数据集更新数据库
2009-04-22 14:07 观海看云 阅读(845) 评论(0) 编辑 收藏 举报此主题阐释如何使用数据集来更新数据库中的数据。还可使用 SqlCommand 直接在数据库中插入、更新和删除数据,记住这一点很重要。理解从数据库填充数据集中涉及的概念将有助于理解当前的主题。
“从数据库填充数据集”中涉及的一些主题包括从数据库检索出数据并且将其放入数据集中,以及数据集是如何独立于且不同于数据库的。一旦加载了 DataSet,就可以修改数据,并且数据集将跟踪更改。
可将 DataSet 视为从数据库检索出的数据的内存内缓存。DataSet 由表、关系和约束的集合组成。在此示例中,将说明如何在数据表 (DataTable) 上使用 Add 方法向数据集添加新数据。Add 方法使用一列所需的数据列或一个数据行 (DataRow)。
// Create a new Connection and SqlDataAdapter
SqlConnection myConnection = new SqlConnection("server=(local)\\VSdotNET;Trusted_Connection=yes;database=northwind");
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter("Select * from Customers", myConnection);
DataSet myDataSet = new DataSet();
DataRow myDataRow;
// Create command builder. This line automatically generates the update commands for you, so you don't
// have to provide or create your own.
SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(mySqlDataAdapter);
// Set the MissingSchemaAction property to AddWithKey because Fill will not cause primary
// key & unique key information to be retrieved unless AddWithKey is specified.
mySqlDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
mySqlDataAdapter.Fill(myDataSet, "Customers");
myDataRow = myDataSet.Tables["Customers"].NewRow();
myDataRow["CustomerId"] = "NewID";
myDataRow["ContactName"] = "New Name";
myDataRow["CompanyName"] = "New Company Name";
myDataSet.Tables["Customers"].Rows.Add(myDataRow);
请注意数据表必须通过 NewRow 方法返回数据行。该方法返回带有适当的数据表架构的数据行对象。在将这个新的数据行添加到行集合 (RowsCollection) 之前,它是独于表的。
可通过访问数据行来更改数据行中的数据。可以使用行集合中的行索引,该行索引通过 Rows 属性来访问:
myDataSet.Tables["Customers"].Rows[0]["ContactName"]="Peach";
还可通过主键值来访问特定行:
DataRow myDataRow1 = myDataSet.Tables["Customers"].Rows.Find("ALFKI");
myDataRow1["ContactName"]="Peach";
此处,“ALFKI”是“Customers”表中主键“CustomerID”的值。使用 SqlDataAdapter 时,从数据库建立该键。如果不是在通过 PrimaryKey 属性使用数据库,则也可以对该键进行设置。
使用 Delete 方法来移除行。请注意,数据集中发生的是逻辑删除,只有将该数据集更新到数据库时,才会导致物理删除。同样地,可以在数据集上使用 RejectChanges,这种情况下将恢复该行。
myDataSet.Tables["Customers"].Rows[0].Delete();
行中保留了原值和新值。RowChanging 事件使您能够同时访问原值和新值,以决定是否继续进行编辑操作。由于保留了原值和新值,因此可以建立开放式锁定和键更改等方案。
在将更改提交回数据库之前,需要设置 InsertCommand、UpdateCommand 和 DeleteCommand 来协调对数据库做出的更改。对于有限的方案,可使用 SqlCommandBuilder 自动生成这些命令,如以下示例中所示:
SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(mySqlDataAdapter);
要将数据从数据集提交到数据库中,请使用 SqlDataAdapter 上的 Update 方法。
mySqlDataAdapter.Update(myDataSet, "Customers");
以下示例说明如何使用 SqlDataAdapter 从数据库获取数据,在数据集中修改数据,然后通过 SqlDataAdapter 将数据提交回数据库。
用CSHARP编写代码如下
namespace HowTo.Samples.ADONET
{
using System;
using System.Data;
using System.Data.SqlClient;
public class updatingdata
{
public static void Main()
{
updatingdata myupdatingdata = new updatingdata();
myupdatingdata.Run();
}
public void Run()
{
SqlConnection myConnection = new SqlConnection("server=(local)\\NetSDK;Trusted_Connection=yes;database=northwind");
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter("select * from customers", myConnection);
SqlDataAdapter mySqlDataAdapter1 = new SqlDataAdapter("select * from orders", myConnection);
// Restore database to it's original condition so sample will work correctly.
Cleanup();
try
{
DataSet myDataSet = new DataSet();
DataRow myDataRow;
// Create command builder. This line automatically generates the update commands for you, so you don't
// have to provide or create your own.
SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(mySqlDataAdapter);
// Set the MissingSchemaAction property to AddWithKey because Fill will not cause primary
// key & unique key information to be retrieved unless AddWithKey is specified.
mySqlDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
mySqlDataAdapter1.MissingSchemaAction = MissingSchemaAction.AddWithKey;
mySqlDataAdapter.Fill(myDataSet,"Customers");
Console.WriteLine("已将数据从 Customers 表加载到数据集中。");
mySqlDataAdapter1.Fill(myDataSet,"Orders");
Console.WriteLine("已将数据从 Orders 表加载到数据集中。");
// ADD RELATION
myDataSet.Relations.Add("CustOrders",myDataSet.Tables["Customers"].Columns["CustomerId"],myDataSet.Tables["Orders"].Columns["CustomerId"]);
// EDIT
myDataSet.Tables["Customers"].Rows[0]["ContactName"]="Peach";
// ADD
myDataRow = myDataSet.Tables["Customers"].NewRow();
myDataRow["CustomerId"] ="新 ID";
myDataRow["ContactName"] = "新姓名";
myDataRow["CompanyName"] = "新公司名称";
myDataSet.Tables["Customers"].Rows.Add(myDataRow);
Console.WriteLine("已将新行插入 Customers。");
// Update Database with SqlDataAdapter
mySqlDataAdapter.Update(myDataSet, "Customers");
Console.WriteLine("已将更新发送到数据库。");
Console.WriteLine("数据集处理已成功完成!");
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
}
public void Cleanup()
{
SqlConnection myConnection = new SqlConnection("server=(local)\\NetSDK;Trusted_Connection=yes;database=northwind");
try
{
// Restore database to it's original condition so sample will work correctly.
myConnection.Open();
SqlCommand CleanupCommand = new SqlCommand("DELETE FROM Customers WHERE CustomerId = 'NewID'", myConnection);
CleanupCommand.ExecuteNonQuery();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
myConnection.Close();
}
}
}
}
该文章转自[站长热线] 原文链接:http://www.hotzz.com/edu/Program/NET/54816.shtml
出处:http://www.cnblogs.com/zhangtao/
文章版权归本人所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器