SqlCommandBuilder的用法

  • SqlCommandBuilder 用來SqlDataAdapter 自動產生SQL語句 ,批量更新DataSet, 不用再爲SqlDataAdapter 寫好 InsertCommand,DeleteCommand,UpdateCommand等Sql語句.如果對DataSet(注意是內存裏)的修改(比如,遍歷ds裏的Tittle表修改某些字段,或者綁定到datagridview修改)可以通過Update自動更新數據庫。當你不爲SqlDataAdapter 指定SqlCommandBuilder的時候,你就必須手動爲 SqlDataAdapter 寫好 InsertCommand,DeleteCommand,UpdateCommand語句,否則是無法調用Update方法來更新的。

  • using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Data.SqlClient;
    
    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            SqlConnection conn;
            DataSet ds;
            SqlDataAdapter sda;
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                DataTable dt = new DataTable();//創建一個表
                dt = ds.Tables[0];//將DataSet中的數據賦值給dt表
                sda.FillSchema(dt, SchemaType.Mapped);  //FillSchema是用來向DataTable中填入詳細的元數據信息的,例如(column names, primary key, constraints等),但不填入數據。
                DataRow dr = dt.Rows.Find(txtID.Text);//表示DataTable中的一行數據
                //設置DataRow中的值
                dr["orderdate"] = txtorderdate.Text;
                dr["ordercode"] = txtordercode.Text;
                dr["materialscode"] = txtmaterialscode.Text;
                dr["materialsquantity"] = txtmaterialsquantity.Text;
    
               //使用SqlCommandBuilder的好處在於你對DataSet(注意是內存裏)的修改(比如,你遍歷ds裏的Tittle表修改某些字段,
               //或者綁定到datagridview修改)可以通過Update自動更新到數據庫
                SqlCommandBuilder cmdbuilder = new SqlCommandBuilder(sda);
                sda.Update(dt);
    
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                conn = new SqlConnection("server =D008;database =GoogolOrderMangment;uid = sa;pwd = 123456");
                SqlCommand cmd = new SqlCommand("select * from materialsdownload ", conn);
                sda = new SqlDataAdapter();
                sda.SelectCommand = cmd;
                ds = new DataSet();
                sda.Fill(ds, "cs");//將數據庫數據填充到dataset數據表中
                dataGridView1.DataSource = ds.Tables[0];
            }
        }
    }
    

     

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章