using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
namespace test1
{
public class Transaction
{
public SqlConnection getCon()
{
string constr="server=localhost;uid=sa;pwd=123456;database=test";
SqlConnection con=new SqlConnection(constr);
return con;
}
public void UpdateWithTran()
{
SqlConnection mycon = getCon();
mycon.Open();
SqlCommand cmd = new SqlCommand();
SqlTransaction mytran = mycon.BeginTransaction();
//绑定数据库连接和事务对象
cmd.Connection = mycon;
cmd.Transaction = mytran;
try
{
cmd.CommandText = "use test";
cmd.CommandText = "update my_test set tname='Aillo' where tid>'0003'";
//cmd.CommandText = "create database Hello";
cmd.ExecuteNonQuery();
mytran.Commit();
}
catch (Exception ex)
{
mytran.Rollback();
Console.Write("事务操作出错,已回滚。系统信息:" + ex.Message);
}
finally
{
mycon.Close();
}
}
}
class Program
{
static void Main(string[] args)
{
Transaction tran = new Transaction();
tran.UpdateWithTran();
}
}
}
很好的方法谢谢你们的