using (SqlConnection conn = new SqlConnection("server=(local);database=TallyMoney;user id=sa;password=sa;"))
{
conn.Open();//连接数据库
SqlTransaction transaction;//开始一个本地事务
transaction = conn.BeginTransaction("MyTransaction");//必须为SqlCommand指定数据库连接和登记的事务
//或transaction = conn.BeginTransaction();
SqlCommand cmd = new SqlCommand("", conn, transaction);
try
{//向数据表中插入记录的命令语句
cmd.CommandText = @"insert into aa (datestr,remarkinfo) values ('"+TextBox1.Text+"','"+TextBox2.Text+"')";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into bb (aa_id,name) values ('"+TextBox3.Text+"','"+TextBox4.Text+"')";
cmd.ExecuteNonQuery();
transaction.Commit();//提交事务
Response.Write("操作完成");
}
catch (Exception ex)
{
Response.Write("提交错误类型:"+ex.GetType());
Response.Write("提交错误信息:"+ex.Message);
try
{
transaction.Rollback();//回滚事务
}
catch (Exception ex2)
{
Response.Write("回滚错误类型:"+ex2.GetType());
Response.Write("回滚错误信息:"+ex2.Message);
}
}
}