当前位置:Gxlcms > 数据库问题 > C# SqlDataAdapter

C# SqlDataAdapter

时间:2021-07-01 10:21:17 帮助过:23人阅读

2. update 方法

  update 方法是用来更改数据库的。也就是,把C#内存中修改的内容同步到数据库中。更新是逐行进行的。对于插入、修改和删除,Update 方法会自动确定类型(Insert、Update 或 Delete)。

 

二、属性

  SqlDataAdapter有5个有用的属性,分别为SelectCommand、InsertCommand、DeleteCommand、UpdateCommand 和TableMappings 属性。其中,TableMappings 表示列的映射关系。其他的属性通过名字就能知道它所做的操作了。

 

 

示例一:

private static DataSet SelectRows(DataSet dataset, string connectionString,string queryString) 
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlDataAdapter adapter = new SqlDataAdapter();
        adapter.SelectCommand = new SqlCommand(queryString, connection);
        adapter.Fill(dataset);
        return dataset;
    }
}

 示例二:

创建 SqlDataAdapter 并将 MissingSchemaAction 设置为 AddWithKey,以便从数据库中检索其他架构信息。SelectCommand、InsertCommand、UpdateCommand 和 DeleteCommand 属性集及其相应的SqlParameter 对象已添加到 Parameters 集合。该方法返回一个 SqlDataAdapter 对象。

public static SqlDataAdapter CreateSqlDataAdapter(SqlConnection connection)

{
  SqlDataAdapter adapter = new SqlDataAdapter();
  adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;

  // Create the commands.
  adapter.SelectCommand = new SqlCommand("SELECT CustomerID, CompanyName FROM CUSTOMERS", connection);
  adapter.InsertCommand = new SqlCommand("INSERT INTO Customers (CustomerID, CompanyName) " + "VALUES (@CustomerID, @CompanyName)",  connection);
  adapter.UpdateCommand = new SqlCommand("UPDATE Customers SET CustomerID = @CustomerID, CompanyName = @CompanyName " + "WHERE   CustomerID = @oldCustomerID", connection);
  adapter.DeleteCommand = new SqlCommand("DELETE FROM Customers WHERE CustomerID = @CustomerID", connection);

  // Create the parameters.
  adapter.InsertCommand.Parameters.Add("@CustomerID", SqlDbType.Char, 5, "CustomerID");
  adapter.InsertCommand.Parameters.Add("@CompanyName", SqlDbType.VarChar, 40, "CompanyName");

  adapter.UpdateCommand.Parameters.Add("@CustomerID", SqlDbType.Char, 5, "CustomerID");
  adapter.UpdateCommand.Parameters.Add("@CompanyName",SqlDbType.VarChar, 40, "CompanyName");
  adapter.UpdateCommand.Parameters.Add("@oldCustomerID", SqlDbType.Char, 5, "CustomerID").SourceVersion = DataRowVersion.Original; 
  adapter.DeleteCommand.Parameters.Add("@CustomerID", SqlDbType.Char, 5, "CustomerID").SourceVersion = DataRowVersion.Original; 
  return adapter;
}

 

参考文献 http://msdn.microsoft.com/zh-cn/library/system.data.sqlclient.sqldataadapter.fill(v=vs.90)

    http://msdn.microsoft.com/zh-cn/library/879f39d8(v=vs.90)

C# SqlDataAdapter

标签:添加   sof   action   key   self   param   nec   修改   操作   

人气教程排行