• ADO.NET:从数据集更新数据库


    此主题阐释如何使用数据集来更新数据库中的数据。还可使用 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

    作者:wpf之家
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    [Step By Step]SAP Visual intelligence连接到SAP HANA并访问视图 沧海
    SAP HANA中的用户拷贝(User Copy) 沧海
    在Cloudshare上使用PAL=〉系统检查及初始化 沧海
    SAP HANA学习资料中的基础表及数据SQL语句汇总 沧海
    [Step By Step]SAP HANA PAL多用户使用(单指数平滑法SINGLESMOOTH) 沧海
    [Step By Step]SAP HANA中创建层次分析视图(Hierarchy Analytic View) 沧海
    [Step By Step]SAP Visual Intelligence新增公式数据列(SAP HANA中提取数据) 沧海
    SAP HANA Education: Course & Certification Program 2013(SAP HANA认证考试) 沧海
    [Step By Step]SAP HANA中创建分析权限(Analytic Privilege) 沧海
    SAP HANA 存储过程中的IF While使用案例 沧海
  • 原文地址:https://www.cnblogs.com/wpf123/p/2347477.html
Copyright © 2020-2023  润新知