有时候,需要一步作业多个sql语句,或者同时把一句插入到不同的数据库中。
这个时候,就要考虑语句执行的同步性。
通常,可以采用事务机制来进行控制。
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Data;
- using System.Data.OracleClient;
- namespace TransSqlDemo
- {
- class Program
- {
- private string connstr = "User ID=CT_ISD01;Data Source=ORATEST.centurydsp.com;Password=ISD01_CT";
- static void Main(string[] args)
- {
- Program p = new Program();
- p.DbOp();
- Console.WriteLine("Execute Successfully");
- Console.Read();
- }
- private void DbOp()
- {
- using (OracleConnection conn = new OracleConnection(connstr))
- {
- conn.Open();
- OracleTransaction trans = null;
- trans = conn.BeginTransaction(); //事务开始
- OracleCommand cmd = conn.CreateCommand();
- cmd.Transaction = trans; //---
- try
- {
- string sql = "insert into ivan_test(id,name) values(15133,'test')";
- string sql2 = "insert into ivan_test(id,name) values(15134,'test')";
- cmd.CommandText = sql;
- cmd.ExecuteNonQuery();
- cmd.CommandText = sql2;
- cmd.ExecuteNonQuery();
- trans.Commit(); //事务提交
- }
- catch (Exception ex)
- {
- trans.Rollback(); //如果出错,则回滚
- throw new Exception(ex.Message);
- }
- finally
- {
- conn.Close();
- }
- }
- }
- }
- }