- static void Main(string[] args)
- {
- SqlConnection sqlConn = new SqlConnection(
- ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString);
- SqlTransaction sqlTrans = null;
- try
- {
- sqlConn.Open();
- sqlTrans = sqlConn.BeginTransaction();//事务开始
- SqlCommand sqlComm = new SqlCommand("", sqlConn, sqlTrans);
- sqlComm.CommandTimeout = 120;
- sqlComm.CommandType = System.Data.CommandType.Text;
- string insertSql = "insert into dbo.TransTestTable values (66,'66');";
- string updateSql = "update dbo.TransTestTable set [Name] = '77' where [Id] = 66;";
- sqlComm.CommandText = insertSql;
- sqlComm.ExecuteNonQuery();//执行insert
- sqlComm.CommandText = updateSql;
- sqlComm.ExecuteNonQuery();//执行update
- //throw new Exception("test exception.the transaction must rollback");
- sqlTrans.Commit();//事务提交
- }
- catch (Exception ex)
- {
- sqlTrans.Rollback();//事务回滚
- Console.WriteLine(ex.Message);
- }
- finally
- {
- if (sqlConn.State != System.Data.ConnectionState.Closed)
- sqlConn.Close();
- }
- Console.ReadLine();
- }