我有以下代码。我不知道为什么我会得到以下错误。 “当分配给命令的连接处于挂起的本地事务中时,ExecuteNonQuery要求命令具有事务。该命令的Transaction属性尚未初始化” 我正在使用SQL事务 请有人帮助我
protected void RunLeave(int posID, int tot, int rowid)
{
using (SqlConnection con = new SqlConnection(Modfunctions.configstring))
{
con.Open();
SqlDataReader dr = default(SqlDataReader);
int i = 0;
try
{
SqlCommand cmd = new SqlCommand("Select ID from Employee WITH(Nolock) WHERE PositionID=@a", con);
cmd.Parameters.Add("@a", SqlDbType.Int).Value = posID;
//cmd.Transaction = transaction;
dr = cmd.ExecuteReader();
if (dr.HasRows)
using (SqlConnection cons = new SqlConnection(Modfunctions.configstring))
{
cons.Open();
SqlTransaction transaction = cons.BeginTransaction(DateTime.Now.ToLongTimeString());
SqlCommand cm = new SqlCommand();
cm.Transaction = transaction;
cm.Connection = cons;
while (dr.Read())
{
cm.CommandText="INSERT INTO LeaveAssignmentEntry VALUES('" + rowid + "','" + ddl.SelectedItem.Text + "','" + dr[0].ToString() + "','" + tot + "','" + tot + "','0')";
cm.ExecuteNonQuery();
i++;
}
transaction.Commit();
}
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", "alert('" + i + " employee(s) run successfully')", true);
}
catch (Exception ex)
{
try
{
//transaction.Rollback();
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", "alert('" + ex.Message.Replace("'", "") + "')", true);
}
catch (Exception ex1)
{
}
}
}
}
答案 0 :(得分:1)
就像你将事务设置为第一个命令一样:
cmd.Transaction = transaction;
同样对你的第二个命令:
cm.Transaction = transaction;
基本上,当您在事务的上下文中时,所有数据库交互都需要使用相同的事务。