using (SqlConnection conn = new SqlConnection("server=192.168.120.209;database=test;uid=sa;pwd=Djhu2013"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
SqlTransaction transaction = conn.BeginTransaction();//开始事物
cmd.Transaction = transaction;
try
{
cmd.Connection = conn;
cmd.CommandText = "insert into test1 values ('lily')select @@IDENTITY";
int paintID = Convert.ToInt32(cmd.ExecuteScalar());
cmd.CommandText = "insert into test2 values(" + paintID + ",'lily')";
cmd.ExecuteNonQuery();
transaction.Commit();//如果都成功那么提交事物
}
catch (Exception ex)
{
Console.Write(ex.Message);
transaction.Rollback();//出现错误,进行回滚
}
}
}