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 < table.Rows.Count; i++) //修改table中每一行的内容
{
dr = table.Rows[i];
dr["f"] = 3; //字段名为f
}
//testB表中必须存在主键,否则无法更新// ****** 这个很重要 *****
sqlAdap.Update(table);
//sqlAdap.Update(dtst, "testB");
sqlConnection.Close();
MessageBox.Show("aa");
下面是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");
}