任务要么全部完成

时间:2022-03-02 04:32:37

为了便利移到了ADO.NET分类里

事务的主要特征是,任务要么全部完成,要么都不完成

事务常用于写入或更新数据库中的数据。将数据写入文件或注册表也可以使用事物。

ADO.NET不撑持跨越多个连接的事物,它总是关联到一个连接上的本地事务。

1.引入dll -----  System.Transactions

2.引入定名空间

using System.Transactions

1.引入dll---- System.Data.OracleClinet

2.引入定名空间

using System.Data.OleDb;

不带事物的多表增删改

string str = ConfigurationManager.AppSettings["con_MES"]; OleDbConnection conn = new OleDbConnection(str); using (conn) { conn.Open(); try { if (conn.State == ConnectionState.Open) { string sql1 = "insert into fruits (name, place, amount) values (‘椰子‘, ‘海南‘, ‘500‘)"; string sql2 = "update pingtable set targetip=‘192.168.55.55‘ where id=1102"; OleDbCommand command1 = new OleDbCommand(sql1, conn); OleDbCommand command2 = new OleDbCommand(sql2, conn); command1.ExecuteNonQuery(); command2.ExecuteNonQuery(); MessageBox.Show("告成插入"); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } MessageBox.Show("*连接");

单个Connection连接事务的多表增删改

string str = ConfigurationManager.AppSettings["con_MES"];//连接字符串 OleDbConnection conn = new OleDbConnection(str); using (conn) { conn.Open(); OleDbTransaction OT=conn.BeginTransaction();//打开连接后才华赋值给事物 try { if (conn.State == ConnectionState.Open) { string sql1 = "insert into fruits (name, place, amount) values (‘椰子‘, ‘海南‘, ‘500‘)"; string sql2 = "update pingtable set targetip=‘192.168.55.55‘ where id=1102"; OleDbCommand command1 = new OleDbCommand(sql1, conn, OT); OleDbCommand command2 = new OleDbCommand(sql2, conn, OT); command1.ExecuteNonQuery(); command2.ExecuteNonQuery(); OT.Commit(); //事务必然要有提交和回滚 MessageBox.Show("告成插入"); } } catch (Exception ex) { OT.Rollback(); MessageBox.Show(ex.Message); } finally { conn.Close(); //using原本可以*连接,这里提前手动加了个*是为了尽早的*连接,这个finally要领可以不写 MessageBox.Show("*连接"); } }

抽出模板

using (OracleConnection connection = new OracleConnection(connectionString)) { connection.Open(); OracleTransaction transaction; transaction = connection.BeginTransaction(); OracleCommand command = connection.CreateCommand(); try { transaction.Commit(); } catch (Exception e) { transaction.Rollback(); throw e; } finally { connection.Close(); } }