gpt4 book ai didi

c# - 当分配给命令的连接处于挂起的本地传输时,ExecuteReader 要求命令具有事务

转载 作者:可可西里 更新时间:2023-11-01 07:55:42 25 4
gpt4 key购买 nike

我必须用单个事务插入两个表,必须实现的查询如下。其次在 SqlDataReader read = comm.ExecuteReader();

获取异常
public void SqlExecuteNonQuery(Customer obj)
{
//string query = "DECLARE @_customerID int ";
string query1 = "INSERT INTO customer (customerName,customerSex,Email) VALUES ('" + obj.name + "','" + obj.sex + "','" + obj.Email + "') ";
//string query2 = "SET @_customerID =@@identity ";
string query3 = "INSERT INTO customerDetails(customerID,customerAddress,customerPhone) VALUES (" + obj.id + ",'" + obj.address + "','" + obj.phone + "') ";

string CS = ConnectionName;

using (SqlConnection conn = new SqlConnection(CS))
{
conn.Open();
using (SqlCommand command = new SqlCommand("SELECT Email FROM Customer where Email ='" + obj.Email + "'", conn))
{
SqlDataReader reader = command.ExecuteReader();

try
{
if (reader.Read())
{
throw new Exception("User already exist for the email");
}

else
{
reader.Close();
using (SqlCommand cmd = GetCommand(query1, conn))
{
SqlTransaction transaction;
transaction = conn.BeginTransaction();

try
{
cmd.Transaction = transaction;
cmd.ExecuteNonQuery();
using (SqlCommand comm = new SqlCommand("Select customerID from Customer where email = '" + obj.Email + "'", conn))
{
SqlDataReader read = comm.ExecuteReader();

try
{
while (read.Read())
{
obj.id = (int)read[0];
}
using (SqlCommand cmd1 = GetCommand(query3, conn))
{
try
{
cmd1.ExecuteNonQuery();
}
catch (Exception ex1)
{
Console.WriteLine("Comit Exception Type: {0}", ex1.GetType());
Console.WriteLine("error in inserting - {0}", ex1.Message);
try
{
transaction.Rollback();
}
catch (Exception ex2)
{
Console.WriteLine("RollBack Exception Type: {0}", ex2.GetType());
Console.WriteLine("Message: {0}", ex2.Message);
}
}
}
transaction.Commit();
Console.WriteLine("Successfull transaction");

}
catch (Exception ex)
{
Console.WriteLine("Error type:", ex.GetType());
Console.WriteLine("Message:", ex.Message);

}
finally {
read.Close();
}

}
}

catch (Exception ex)
{
Console.WriteLine("Comit Exception Type: {0}", ex.GetType());
Console.WriteLine("error in inserting - {0}", ex.Message);
try
{
transaction.Rollback();
}
catch (Exception ex2)
{
Console.WriteLine("RollBack Exception Type: {0}", ex2.GetType());
Console.WriteLine("Message: {0}", ex2.Message);
}
}
finally
{
transaction.Dispose();
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

}
}
}

最佳答案

问题是您在与 cmd 相同的连接上执行 cmd1,因此该连接上有一个打开的事务,但您没有设置 cmd1.Transaction ...所以解决方案是

cmd1.Transaction = transaction;

之前

cmd1.ExecuteNonQuery();

关于c# - 当分配给命令的连接处于挂起的本地传输时,ExecuteReader 要求命令具有事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21038357/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com