如果在项目中遇到用户在客户端编辑数据,添加数据.SQL整体更新到数据库里面,应该怎么做呢?下面就将教您如何进行SQL整体更新,供您参考。
数据库结构:
- DataSet ds=new DataSet();读取数据
- private void button1_Click(object sender, System.EventArgs e)
- {
- //
- string str_Conn="workstation id=JHTCHINA;packet size=4096;user id=sa;initial catalog=master;persist security info=False";
- try
- {
- SqlConnection objConn=new SqlConnection(str_Conn);
- string str_sql="select * from Test_Base";
- SqlCommand objComm=new SqlCommand(str_sql,objConn);
- SqlDataAdapter objAdapter=new SqlDataAdapter(objComm);
- objAdapter.Fill(ds,"Test_Base");
- dataGrid1.DataSource=ds;
- }
- catch (Exception exc)
- {
- MessageBox.Show(exc.Message);
- }
- }
CREATE TABLE [Test_Base] (
[CodeZZB] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[InterName] [nvarchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
[Guid] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_LoginPerson_Guid] DEFAULT (newid()),
CONSTRAINT [PK_Test_Base] PRIMARY KEY CLUSTERED
(
[CodeZZB]
) ON [PRIMARY]
) ON [PRIMARY]
GO
定义 全局DataSet
- DataSet ds=new DataSet();读取数据
- private void button1_Click(object sender, System.EventArgs e)
- {
- //
- string str_Conn="workstation id=JHTCHINA;packet size=4096;user id=sa;initial catalog=master;persist security info=False";
- try
- {
- SqlConnection objConn=new SqlConnection(str_Conn);
- string str_sql="select * from Test_Base";
- SqlCommand objComm=new SqlCommand(str_sql,objConn);
- SqlDataAdapter objAdapter=new SqlDataAdapter(objComm);
- objAdapter.Fill(ds,"Test_Base");
- dataGrid1.DataSource=ds;
- }
- catch (Exception exc)
- {
- MessageBox.Show(exc.Message);
- }
- }
编辑添加dataGrid以后更新数据
- private void button2_Click(object sender, System.EventArgs e)
- {
- try
- {
- //这里ds.Table[0]里面的数据已经改变
- string str_Conn="workstation id=JHTCHINA;packet size=4096;user id=sa;initial catalog=master;persist security info=False";
- //整体把修改的数据更新到数据库里面
- SqlConnection objConn=new SqlConnection(str_Conn);
- string str_sql="select * from Test_Base";
- SqlCommand objComm=new SqlCommand(str_sql,objConn);
- SqlDataAdapter objAdapter=new SqlDataAdapter(objComm);
- SqlCommandBuilder updataBulid=new SqlCommandBuilder(objAdapter);
- objAdapter.Update(ds,"Test_Base");
- MessageBox.Show("OK");
- }
- catch (Exception exc)
- {
- MessageBox.Show(exc.Message);
- }
- }
运行通过
如果是SQL整体更新添加,在数据读取的时候
string str_sql="select * from Test_Base where 1=2";
一句代码就可以了
【编辑推荐】
逐条更新数据的SQL语句写法