用SqlDataAdapter与datagridview配合实现快速CRUD

private void btnSave_Click(object sender, EventArgs e)
{
//把DataGridView的修改的数据保存到数据库中去。
string connSql = ConfigurationManager.ConnectionStrings["sql"].ConnectionString;

//修改的sql一定要跟 查询的sql脚本一致。
string sql =
@"Select UserId, UserName, UserAge, DelFlag, CreateDate, UserPwd, LastErrorDateTime, ErrorTimes from userInfo";
using (SqlDataAdapter adapter = new SqlConnection(sql,connSql))
{
//拿到修改后的datatable对象
DataTable dt=dgvUserInfo.DataSource as DataTable;
//用SqlCommandBuider帮我们的Adapter生成相关的CRUD command
using(SqlCommandBuilder cmdBuilder=new SqlCommandBuilder(adapter))
{//将内存表dt映射到数据库的变化
adapter.Update(dt);
}
//
}
SqlDataAdapter含有CRUD4条指令,可以手工写入,也可以用 SqlCommandBuilder注入。这样只要在adapter中传输查询指令,就可以自动生成四条指令。
原文地址:https://www.cnblogs.com/ccjungle/p/7922390.html