以前經常用sql語句(update)更新數據庫,有使用用起來不是很方便,特別是數據量比較大的情況下(比如數據表)很麻煩~~後來感覺用DataSet更新數據庫是不錯的選擇.於是急着寫了一個用ataSet更新數據庫的類如下:(後面有使用說明,總結)
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace winApplication
{
public class sqlAccess
{
//與SQL Server的連接字符串設置
private string _connString;
private string _strSql;
private SqlCommandBuilder sqlCmdBuilder;
private DataSet ds = new DataSet();
private SqlDataAdapter da;
public sqlAccess(string connString,string strSql)
{
this._connString=connString;
}
private SqlConnection GetConn()
{
try
{
SqlConnection Connection = new SqlConnection(this._connString);
Connection.Open();
return Connection;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message,"數據庫連接失敗");
throw;
}
}
//根據輸入的SQL語句檢索數據庫數據
public DataSet SelectDb(string strSql,string strTableName)
{
try
{
this._strSql = strSql;
this.da = new SqlDataAdapter(this._strSql,this.GetConn());
this.ds.Clear();
this.da.Fill(ds,strTableName);
return ds;//返回填充了數據的DataSet,其中數據表以strTableName給出的字符串命名
}
catch (Exception ex)
{
MessageBox.Show(ex.Message,"數據庫操作失敗");
throw;
}
}
//數據庫數據更新(傳DataSet和DataTable的對象)
public DataSet UpdateDs(DataSet changedDs,string tableName)
{
try
{
this.da = new SqlDataAdapter(this._strSql,this.GetConn());
this.sqlCmdBuilder = new SqlCommandBuilder(da);
this.da.Update(changedDs,tableName);
changedDs.AcceptChanges();
return changedDs;//返回更新了的數據庫表
}
catch (Exception ex)
{
MessageBox.Show(ex.Message,"數據庫更新失敗");
throw;
}
}
使用說明總結:
1. GetConn方法創建一個數據庫連接,返回SqlConnection。
2.使用的select命令中必須包含主鍵,這點大家都知道的!
3. this.da.Fill(ds,strTableName) 填充數據集
4.構造CommandBuilder對象時,將DataAdapter對象作爲構造函數參數傳入:
this.sqlCmdBuilder = new SqlCommandBuilder(da);
5. 在調用UpdateDs()更新數據庫前,請檢查changedDs是否已經被更新過,用changedDs.[tableName] GetChanges() != null;
6.用this.da.Update(changedDs,tableName)方法更新數據,然後調用changedDs.AcceptChanges()才能真正的更新數據庫,調用 changedDs.RejectChanges() 取消更新。(轉)