SQL整體更新的方法
如果在項目中遇到用戶在客戶端編輯數(shù)據(jù),添加數(shù)據(jù).SQL整體更新到數(shù)據(jù)庫里面,應該怎么做呢?下面就將教您如何進行SQL整體更新,供您參考。
數(shù)據(jù)庫結(jié)構:
- DataSet ds=new DataSet();讀取數(shù)據(jù)
- 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();讀取數(shù)據(jù)
- 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以后更新數(shù)據(jù)
- private void button2_Click(object sender, System.EventArgs e)
- {
- try
- {
- //這里ds.Table[0]里面的數(shù)據(jù)已經(jīng)改變
- string str_Conn="workstation id=JHTCHINA;packet size=4096;user id=sa;initial catalog=master;persist security info=False";
- //整體把修改的數(shù)據(jù)更新到數(shù)據(jù)庫里面
- 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整體更新添加,在數(shù)據(jù)讀取的時候
string str_sql="select * from Test_Base where 1=2";
一句代碼就可以了
【編輯推薦】
逐條更新數(shù)據(jù)的SQL語句寫法