/// <summary>
/// 文件名称:sqldataupdater.cs
/// 摘 要:sql数据更新器,可方便对单数据表进行读,写,删操作,构造函数按引用传出结果集.
/// sqldataupdater du = new sqldataupdater(sqlhere,ref yourdataset)
/// 调用update(ds)更新数据,自动事务处理,出错信息存在 errormessage.
///
/// 完成日期:2005-4-21
/// 作 者:魏孙鼎
/// 当前版本:1.0
/// </summary>
public class sqldataupdater
{
private sqlconnection cn;
private sqlcommand cmd;
private sqldataadapter da;
private sqltransaction tran;
private sqlcommandbuilder cmdbuilder;
private string err;
public string errormessage
{
get
{
return err;
}
}
/// <summary>
/// 初始化数据更新器
/// </summary>
/// <param name="sql">用于返回schema的sql</param>
/// <param name="dataset">按引用传递的数据集</param>
public sqldataupdater(string sql,ref dataset dataset)
{
err = "";
if (dataset == null) dataset = new dataset();
cn = new sqlconnection(zmarketdata.datasetting.connectionstring);
cmd = new sqlcommand(sql,cn);
da = new sqldataadapter(cmd);
cmdbuilder = new sqlcommandbuilder(da);
da.fill(dataset);
}
public bool update(dataset ds)
{
bool success = false;
cn.open();
tran = cn.begintransaction();
cmd.transaction = tran;
try
{
if(ds.getchanges() != null)
{
da.update(ds.getchanges());
}
success = true;
tran.commit();
}
catch(exception ex)
{
tran.rollback();
err = ex.message;
success = false;
}
return success;
}
~sqldataupdater()
{
da.dispose();
cmd.dispose();
cn.dispose();
}
}
// 应用示例
dataset ds = new dataset();
sqldataupdater du = new sqldataupdater("select * from public_feedback where 1=2",ref ds);
datarow dr = ds.tables[0].newrow();
dr["createdate"] = datetime.now;
dr["firstname"] = request["txtname"];
dr["companyname"] = request["txtcompany"];
dr["email"] = request["txtemail"];
ds.tables[0].rows.add(dr);
if (du.update(ds))
{
//成功
}
else
{
response.write(du.errormessage);
}
新闻热点
疑难解答