以前經(jīng)常用sql語句(update)更新數(shù)據(jù)庫,有使用用起來不是很方便,特別是數(shù)據(jù)量比較大的情況下(比如數(shù)據(jù)表)很麻煩~~后來感覺用DataSet更新數(shù)據(jù)庫是不錯的選擇.于是急著寫了一個用DataSet更新數(shù)據(jù)庫的類如下:(后面有使用說明,總結)
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,"數(shù)據(jù)庫連接失敗" );
throw;
}
}
//根據(jù)輸入的SQL語句檢索數(shù)據(jù)庫數(shù)據(jù)
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;
//返回填充了數(shù)據(jù)的DataSet,其中數(shù)據(jù)表以strTableName給出的字符串命名
}
catch ( Exception ex )
{
MessageBox.Show( ex.Message,"數(shù)據(jù)庫操作失敗" );
throw;
}
}
//數(shù)據(jù)庫數(shù)據(jù)更新( 傳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;
//返回更新了的數(shù)據(jù)庫表
}
catch ( Exception ex )
{
MessageBox.Show( ex.Message,"數(shù)據(jù)庫更新失敗" );
throw;
}
}
使用說明總結:
1. GetConn方法創(chuàng)建一個數(shù)據(jù)庫連接,返回SqlConnection.
2.使用的selectming令中必須包含主鍵,這點大家都知道的!
3. this.da.Fill( ds,strTableName ) 填充數(shù)據(jù)集
4.構造CommandBuilder對象時,將DataAdapter對象作為構造函數(shù)參數(shù)傳入:
this.sqlCmdBuilder = new SqlCommandBuilder( da );
5. 在調用UpdateDs( )更新數(shù)據(jù)庫前,請檢查changedDs是否已經(jīng)被更新過,用
changedDs.[tableName] GetChanges( ) != null;
6.用 this.da.Update( changedDs,tableName )方法更新數(shù)據(jù),然后調用changedDs.AcceptChanges( )才能真正的更新數(shù)據(jù)庫,調用 changedDs.RejectChanges( ) 取消更新.
新聞熱點
疑難解答
圖片精選