程序实例:
1. sql server
sqlconnection myconn=getconn();
myconn.open();
sqlcommand mycomm=new sqlcommand();
sqltransaction mytran; //创建一个事务
mytran=myconn.begintransaction(); //注意,sqltransaction类无公开的构造函数
//从此开始,基于该连接的数据操作都被认为是事务的一部分
mycomm.connection=myconn;
mycomm.transaction=mytran;
mycomm.commandtext="use pubs";
mycomm.executenonquery();
mycomm.commandtext="update roysched set royalty = royalty * 1.10 where title_id like 'pc%'";
mycomm.executenonquery();
mytran.commit(); //提交事务
2.下面的示例创建一个 oracleconnection 和一个 oracletransaction。它还演示了如何使用 begintransaction、commit 和 rollback 方法。
public void runoracletransaction(string myconnstring)
{
oracleconnection myconnection = new oracleconnection(myconnstring);
myconnection.open();
oraclecommand mycommand = myconnection.createcommand();
oracletransaction mytrans;
// start a local transaction
mytrans = myconnection.begintransaction(isolationlevel.readcommitted);
// assign transaction object for a pending local transaction
mycommand.transaction = mytrans;
try
{
mycommand.commandtext = "insert into dept (deptno, dname, loc) values (50, 'technology', 'denver')";
mycommand.executenonquery();
mycommand.commandtype= commandtype.storedprocedure;
mycommand.commandtext="prc_test";
mycommand.executenonquery();
mytrans.commit();
console.writeline("both records are written to database.");
}
catch(exception e)
{
mytrans.rollback();
console.writeline(e.tostring());
console.writeline("neither record was written to database.");
}
finally
{
myconnection.close();
}
}
新闻热点
疑难解答
图片精选