为什么这个事务会出错?
string constr = ConfigurationManager.ConnectionStrings[ "TestConnectionString "].ConnectionString;
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlTransaction tran = con.BeginTransaction();
//生成汇总表
string sqlText1 = "Insert into ... ";
sqlText1 += "... ";
SqlCommand cmd1 = new SqlCommand(sqlText1, con);
cmd1.Parameters.Add(new SqlParameter( "@GZYear ", SqlDbType.Char, 4));
cmd1.Parameters.Add(new SqlParameter( "@GZMonth ", SqlDbType.Char, 2));
//向汇总表插入相应的数据
string sqlText2 = "Update ... ";
sqlText2 += ", ... ";
sqlText2 += ", ... ";
SqlCommand cmd2 = new SqlCommand(sqlText2, con);
cmd2.Parameters.Add(new SqlParameter( "@GZYear ", SqlDbType.Char, 4));
cmd2.Parameters.Add(new SqlParameter( "@GZMonth ", SqlDbType.Char, 2));
try
{
cmd1.Parameters[ "@GZYear "].Value = (String)Session[ "GZYear "];
cmd1.Parameters[ "@GZMonth "].Value = (String)Session[ "GZMonth "];
cmd1.ExecuteNonQuery();
cmd2.Parameters[ "@GZYear "].Value = (String)Session[ "GZYear "];
cmd2.Parameters[ "@GZMonth "].Value = (String)Session[ "GZMonth "];
cmd2.ExecuteNonQuery();
tran.Commit();
showMsg( "生成汇总数据成功,事务已提交! ");
}
catch(Exception ex)
{
tran.Rollback();
showMsg( "生成汇总数据失败,事务已回滚! \\n错误信息: " + ex.Message.ToString());
}
finally
{
tran.Dispose();
cmd1.Dispose();
cmd2.Dispose();
con.Close();
con.Dispose();
}
ex提示 "如果分配命令的连接位于本地挂起事务,ExcuteNonQuery要求命令拥有事务.命令的Transaction属性尚未初始化 "
这是什么意思呀?我究竟错在哪里呢?
我上面的事务主要是想从其它表中提取数据插入到指定表A中,然后执行向A表执行关联的更新操作.
[解决办法]
SqlConnection myConnection = new SqlConnection( "Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI; ");
myConnection.Open();
// 启动一个事务
SqlTransaction myTrans = myConnection.BeginTransaction();
// 为事务创建一个命令
SqlCommand myCommand = new SqlCommand();
myCommand.Connection=myConnection;
myCommand.Transaction = myTrans;
try
{
myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (100, "Description ") ";
myCommand.ExecuteNonQuery();
myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (101, "Description ") ";
myCommand.ExecuteNonQuery();
//提交事务处理
myTrans.Commit();
}
catch(Exception ex)
{
myTrans.Rollback();
}
finally
{
myConnection.Close();
}