asp.net创建事务的方法
程序员文章站
2023-02-15 19:12:43
1、建立list用于存放多条语句
///
/// 保存表单
///
///
1、建立list用于存放多条语句
/// <summary> /// 保存表单 /// </summary> /// <param name="context"></param> protected void save() { list<string> list = new list<string>(); list.add(string.format("insert into picsone(model,idser,idflg,lmuser,lmdate,lmtime) values('{0}','{1}','{2}','{3}',{4},{5})", "t1002", "y", "n", "u001", 20161103, 140025)); list.add(string.format("insert into picstwo(model,idser,idflg,lmuser,lmdate,lmtime) values('{0}','{1}','{2}','{3}',{4},{5})", "t1002", "y", "n", "u001", 20161103, 140025)); bool bol = executetransaction(list); if (bol) { messagebox.show("保存成功!"); } else { messagebox.show("保存失败!"); } }
2、调用executetransaction方法,并返回返回值true为成功,false为失败,语句并回滚
/// <summary> /// 执行语句 /// </summary> /// <param name="list"></param> /// <returns></returns> private bool executetransaction(list<string> list) { using (sqlconnection connection = new sqlconnection(configurationmanager.appsettings["localconnectionstring"].tostring())) { sqlcommand command = new sqlcommand(); sqltransaction transaction = null; try { connection.open(); transaction = connection.begintransaction(); command.connection = connection; command.transaction = transaction; for (int i = 0; i < list.count; i++) { command.commandtext = list[i]; command.executenonquery(); } transaction.commit(); connection.close(); return true; } catch { transaction.rollback(); connection.close(); return false; } } }