using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Locaris.LJKDep.AdoNet { public partial class SqlCommandBuilderCRUDFrm : Form { public SqlCommandBuilderCRUDFrm() { InitializeComponent(); } private void SqlCommandBuilderCRUD_Load(object sender, EventArgs e) { string sqlConnectString = SqlHelper.GetSqlConnectString(); string sqlCommandText = @"SELECT [User_ID] ,[User_Name] ,[User_Gender] ,[User_Age] ,[User_Address] ,[User_Birthday] ,[User_Remark] ,[User_Money] ,[User_GUIDDemo] ,[User_Pwd] FROM[LJK_SQLServerDB].[dbo].[User_Info]"; using (SqlDataAdapter adapter = new SqlDataAdapter(sqlCommandText, sqlConnectString)) { DataSet dataSet = new DataSet(); adapter.Fill(dataSet, "UserInfo"); this.dgvUserInfo.DataSource = dataSet.Tables["UserInfo"]; } } #region 将修改的数据保存到数据库中,adapter与SqlCommandBuilder自动实现增删改查 private void button1_Click(object sender, EventArgs e) { //把DataGirdView中的数据保存到数据库中。 //修改的Sql脚本一定与查询的SQL脚本一致。 string connSqlString = SqlHelper.GetSqlConnectString(); string sqlCommandText = @"SELECT [User_ID] ,[User_Name] ,[User_Gender] ,[User_Age] ,[User_Address] ,[User_Birthday] ,[User_Remark] ,[User_Money] ,[User_GUIDDemo] ,[User_Pwd] FROM[LJK_SQLServerDB].[dbo].[User_Info]"; ; using (SqlDataAdapter adapter=new SqlDataAdapter(sqlCommandText,connSqlString)) { //拿到修改完后的DataTable对象 DataTable dataSource = this.dgvUserInfo.DataSource as DataTable; //* ----- SqlCommandBuilder帮助我们的Adapter生成相关的CRUD的命令 sqlCommand -------* using (SqlCommandBuilder sqlCommandBuilder=new SqlCommandBuilder(adapter)) { adapter.Update(dataSource); //将修改完后的表(上一步中转成了内存表)的数据映射回数据库中 } //adapter的使用 //SqlCommand adapterDeleteCommand = adapter.DeleteCommand; 删除 //SqlCommand adapterInsertCommand = adapter.InsertCommand; 插入 //SqlCommand adapterSelectCommand = adapter.SelectCommand; 选择 //SqlCommand adapterUpdateCommand = adapter.UpdateCommand; 修改 } MessageBox.Show("保存成功了!!!"); //刷新数据,重新加载 } #endregion } }