欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  数据库

DataTable修改后,如何更新数据库

程序员文章站 2022-05-10 11:15:59
...

DataTable中的数据可以修改多个后,同时更新到数据库,这样比较方便。下面是实现的代码: DataTable table = new DataTable();//初始化一个DataTable对象 string sqlConnectionString = Data Source=ComputerName-PC;Initial Catalog=charge_sys;User ID=sa;

DataTable中的数据可以修改多个后,同时更新到数据库,这样比较方便。下面是实现的代码:

            DataTable table = new DataTable();//初始化一个DataTable对象
            
            string sqlConnectionString = "Data Source=ComputerName-PC;Initial Catalog=charge_sys;User ID=sa;PWD=123456;";
            SqlConnection sqlConnection = new SqlConnection(sqlConnectionString);//连接数据库
            
            SqlCommand sqlCommand = new SqlCommand("select * from testB", sqlConnection);
            
            SqlDataAdapter sqlAdap = new SqlDataAdapter(sqlCommand);
            SqlCommandBuilder sqlBuilder = new SqlCommandBuilder(sqlAdap);//这句挺重要的,好像是批量更新的时候用
            
            //DataSet dtst = new DataSet();      用dataSet也可以完成,下面有对应实现的代码

            sqlConnection.Open();
            sqlAdap.Fill(table);
       
            //table = dtst.Tables["testB"];

            DataRow dr = table.Rows[0];//第一行
            
            //dr.BeginEdit();
            //dr.EndEdit();     貌似这两句主要是数据绑定到控件的时候才用

            for (int i = 0; i 

下面是DataTable与dataGridView 控件绑定,当dataGridView中的数据改变时,更新数据库的代码:


DataTable和dataGridView控件绑定代码:

private void Form1_Load(object sender, EventArgs e)
        {
            string sqlConnectionString = "Data Source=ComputerName-PC;Initial Catalog=charge_sys;User ID=sa;PWD=123456;";
            SqlConnection sqlConnection = new SqlConnection(sqlConnectionString);//初始化sqlconnection

            DataTable table = new DataTable();
            SqlDataAdapter sqlAdap = new SqlDataAdapter("select * from testB ", sqlConnection);

            sqlConnection.Open();
            sqlAdap.Fill(table);
            sqlConnection.Close();

            //将testB表中的数据显示在dataGridView中
            this.dataGridView1.DataSource = table;

        }

实现将dataGridView中的改动更新到数据库代码:


private void butUpdate_Click(object sender, EventArgs e)
        {
            DataTable table = new DataTable();
            table = (DataTable)this.dataGridView1.DataSource;

            string sqlConnectionString = "Data Source=WangHaitao-PC;Initial Catalog=charge_sys;User ID=sa;PWD=123456;";
            SqlConnection sqlConnection = new SqlConnection(sqlConnectionString);
            
            SqlCommand sqlCommand = new SqlCommand("select * from testB", sqlConnection);
            
            SqlDataAdapter sqlAdap = new SqlDataAdapter(sqlCommand);
            SqlCommandBuilder sqlBuilder = new SqlCommandBuilder(sqlAdap);//必须有

            sqlConnection.Open();
            sqlAdap.Fill(table);

            //testB表中必须存在主键,否则无法更新
            sqlAdap.Update(table);

            sqlConnection.Close();
            MessageBox.Show("aa");

        }