private void updateToolStripMenuItem_Click(object sender, EventArgs e)
{//将数据更新回数据库
//获取源数据
DataTable dt = dataGridView1.DataSource as DataTable;
if (dt != null)
{
string connStr = "Data Source=(local);Initial Catalog=hem09;User ID=sa;Password=123456";
using (SqlConnection conn = new SqlConnection(connStr))
{
//构造适配器对象
SqlDataAdapter adapter = new SqlDataAdapter();
//构造修改语句
string sql = "update employee set ename=@name,ecode=@code where eid=@id";
//构造用于修改的命令对象
SqlCommand cmdUpdate = new SqlCommand(sql, conn);
cmdUpdate.Parameters.Add("@name", SqlDbType.NVarChar, 10, "ename");
cmdUpdate.Parameters.Add("@code", SqlDbType.VarChar, 18, "ecode");
cmdUpdate.Parameters.Add("@id", SqlDbType.Int, 4, "eid");
//构造适配器的修改命令属性
adapter.UpdateCommand = cmdUpdate;
conn.Open();
//完成数据更新,会逐条的对比数据
//情况1:dt中有的数据,而数据库中没有,则会调用InsertCommand执行
//情况2:dt中没有的数据,而数据库中有,则会调用DeleteCommand执行
//情况3:都有,但是不一样,则会调用UpdateCommand执行
adapter.Update(dt);
}
}
}