SqlCommandBuilder在用SqlDataReader更新数据源时的作用

本文介绍如何使用SqlCommandBuilder与SqlDataAdapter结合进行数据库更新操作。通过实例演示了如何通过SqlCommandBuilder自动生成增删改语句,简化数据同步过程。

用于将对 DataSet 所做的更改与关联的 SQL Server 数据库的更改相协调。

SqlDataAdapter 不会自动生成实现 DataSet 的更改与关联的 SQL Server 实例之间的协调所需的 Transact-SQL 语句。但是,如果设置了 SqlDataAdapter SelectCommand 属性,则可以创建一个 SqlCommandBuilder 对象来自动生成用于单表更新的 Transact-SQL 语句。然后,SqlCommandBuilder 将生成其他任何未设置的 Transact-SQL 语句。

关于如何向数据库传数据,以前我的数据都是采用Sql代码用SqlCommand一条一条语句的传入数据库。但是现在将SqlCommandBuilderSqlDataAdapter结合使用,可以方便地去数据库进行更新。只要指定Select 语句就可以自动生成Insertupdate,delete语句,但要注意一点。Select 语句中返回的列要包括主键列,否则将无法产生Update,Delete语句

 

构造函数 public SqlCommandBuilder (SqlDataAdapter adapter)

使用关联的 SqlDataAdapter 对象初始化 SqlCommandBuilder 类的新实例。

示例:SqlCommandBuilderSqlDataAdapter结合使用,对数据库进行更新

     查询tb_command表中的所有数据并显示在DataGridView中,单击某条数据会显示其详细信息。当对某条数据修改后,单击修改按钮,将调用SqlDataReader对象的update方法更新数据源。

namespace UpdateDataSet

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        SqlConnection conn;                                         //声明一个SqlConnection变量

        DataSet ds;                                                      //声明一个DataSet变量

        SqlDataAdapter sda;                                         //声明一个SqlDataAdapter变量

        private void Form1_Load(object sender, EventArgs e)

        {

            //实例化SqlConnection变量conn,连接数据库

            conn = new SqlConnection("server=.;database=db_14;uid=sa;pwd=911013");

            //创建一个SqlCommand对象

            SqlCommand cmd = new SqlCommand("select * from tb_command", conn);

            sda = new SqlDataAdapter();                      //实例化SqlDataAdapter对象

            sda.SelectCommand = cmd;                       //设置SqlDataAdapter对象的SelectCommand属性为cmd

            ds = new DataSet();                                         //实例化DataSet

            sda.Fill(ds, "tb_command");                       //使用SqlDataAdapter对象的Fill方法填充DataSet

            dataGridView1.DataSource = ds.Tables[0];//设置dataGridView1控件的数据源

        }

        private void button1_Click(object sender, EventArgs e)

        {

            DataTable dt = ds.Tables["tb_command"];      //创建一个DataTable

            sda.FillSchema(dt, SchemaType.Mapped);       //把表结构加载到tb_command表中 一定不能少。 SqlDataAdapter 填充 DataSet 时,它为返回的数据创建必需的表和列(如果这些表和列尚不存在)。但是,除非 MissingSchemaAction 属性设置为 AddWithKey,否则这个隐式创建的架构中不包括主键信息。也可以使用 FillSchema,让 SqlDataAdapter 创建 DataSet 的架构,并在用数据填充它之前就将主键信息包括进去。将SqlCommandBuilderSqlDataAdapter结合使用,可以方便地去数据库进行更新。只要指定Select 语句就可以自动生成Insertupdate,delete语句,但要注意一点。Select 语句中返回的列要包括主键列,否则将无法产生Update,Delete语句

 

 

            DataRow dr = dt.Rows.Find(txtNo.Text);  //创建一个DataRow

            //设置DataRow中的值

            dr["姓名"] = txtName.Text.Trim();

            dr["性别"] = this.txtSex.Text.Trim();

            dr["年龄"] = this.txtAge.Text.Trim();

            dr["奖金"] = this.txtJJ.Text.Trim();

            //实例化一个SqlCommandBuilder

            SqlCommandBuilder cmdbuider = new SqlCommandBuilder(sda);

            //调用其Update方法将DataTable更新到数据库中

            sda.Update(dt);

           

        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)

        {

            //dataGridView1控件的CellClick事件中实现单击某条数据显示详细信息

            txtNo.Text = dataGridView1.SelectedCells[0].Value.ToString();

            txtNo.ReadOnly = true;

            txtName.Text = dataGridView1.SelectedCells[1].Value.ToString();

            txtSex.Text = dataGridView1.SelectedCells[2].Value.ToString();

            txtAge.Text = dataGridView1.SelectedCells[3].Value.ToString();

            txtJJ.Text = dataGridView1.SelectedCells[4].Value.ToString();

        }

 

      

    }

}

using System;using System.Collections.Generic;using System.Text;using System.Data;using System.Data.SqlClient; namespace DatabaseOperate{ class SqlOperateInfo { //Suppose your ServerName is "aa",DatabaseName is "bb",UserName is "cc", Password is "dd" private string sqlConnectionCommand = "Data Source=aa;Initial Catalog=bb;User ID=cc;Pwd=dd"; //This table contains two columns:KeywordID int not null,KeywordName varchar(100) not null private string dataTableName = "Basic_Keyword_Test"; private string storedProcedureName = "Sp_InertToBasic_Keyword_Test"; private string sqlSelectCommand = "Select KeywordID, KeywordName From Basic_Keyword_Test"; //sqlUpdateCommand could contain "insert" , "delete" , "update" operate private string sqlUpdateCommand = "Delete From Basic_Keyword_Test Where KeywordID = 1"; public void UseSqlReader() { SqlConnection sqlConnection = new SqlConnection(sqlConnectionCommand); SqlCommand sqlCommand = new SqlCommand(); sqlCommand.CommandType = System.Data.CommandType.Text; sqlCommand.Connection = sqlConnection; sqlCommand.CommandText = sqlSelectCommand; sqlConnection.Open(); SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); while(sqlDataReader.Read()) { //Get KeywordID and KeywordName , You can do anything you like. Here I just output them. int keywordid = (int)sqlDataReader[0]; //the same as: int keywordid = (int)sqlDataReader["KeywordID"] string keywordName = (string)sqlDataReader[1]; //the same as: string keywordName = (int)sqlDataReader["KeywordName"] Console.WriteLine("KeywordID = " + keywordid + " , KeywordName = " + keywordName); } sqlDataReader.Close(); sqlCommand.Dispose(); sqlConnection.Close(); } public void UseSqlStoredProcedure() { SqlConnection sqlConnection = new SqlConnection(sqlConnectionCommand); SqlCommand sqlCommand = new SqlCommand(); sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.Connection = sqlConnection; sqlCommand.CommandText = storedProcedureName; sqlConnection.Open(); sqlCommand.ExecuteNonQuery(); //you can use reader here,too.as long as you modify the sp and let it like select * from .... sqlCommand.Dispose(); sqlConnection.Close(); } public void UseSqlDataSet() { SqlConnection sqlConnection = new SqlConnection(sqlConnectionCommand); SqlCommand sqlCommand = new SqlCommand(); sqlCommand.CommandType = System.Data.CommandType.Text; sqlCommand.Connection = sqlConnection; sqlCommand.CommandText = sqlSelectCommand; sqlConnection.Open(); SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(); sqlDataAdapter.SelectCommand = sqlCommand; DataSet dataSet = new DataSet(); //sqlCommandBuilder is for update the dataset to database SqlCommandBuilder sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter); sqlDataAdapter.Fill(dataSet, dataTableName); //Do something to dataset then you can update it to Database.Here I just add a row DataRow row = dataSet.Tables[0].NewRow(); row[0] = 10000; row[1] = "new row"; dataSet.Tables[0].Rows.Add(row); sqlDataAdapter.Update(dataSet, dataTableName); sqlCommand.Dispose(); sqlDataAdapter.Dispose(); sqlConnection.Close(); } }}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值