【发布时间】:2016-08-29 12:13:06
【问题描述】:
我有以下代码(简化)来访问我的数据库。我知道使用语句和参数,但我缩短了它以集中我的问题。
string ConnectionString = "ConnectionStringHere";
//1. insert Transaction
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlTransaction myTrans = myConnection.BeginTransaction();
string sUpdate = "INSERT INTO User (FirstName, LastName) VALUES ('jon','doe')";
SqlCommand myCommand = new SqlCommand(sUpdate, myConnection, myTrans);
myCommand.ExecuteNonQuery();
//2. select from the same table
SqlConnection myConnection2 = new SqlConnection(ConnectionString);
string sSelect = "SELECT FirstName, LastName FROM User WHERE ID = 123";
DataTable dtResult = new DataTable();
SqlDataAdapter myDataAdapter2 = new SqlDataAdapter(sSelect, myConnection2);
myDataAdapter2.Fill(dtResult); //TimeOut Exception here
//submit changes from my transaction here
myTrans.Commit();
在第二部分中,我得到一个 TimeOutExcetion,因为我无法访问我的 User 表,直到我提交我的事务 myTrans.Commit(); 之后 - 死锁。
我的问题是 - 在这里避免死锁的最佳做法是什么?我可以通过将SELECT 作为事务的一部分或设置IsolationLevel
SqlTransaction myTrans = myConnection.BeginTransaction(IsolationLevel.ReadUncommitted);
但我不确定这些的用法。我不必担心无效数据,因为我总是按 ID 选择。
【问题讨论】:
-
你现在连连接都没有打开,是你的真实密码吗?使用
using-statement -
@Tim,没有非真实代码
-
当前问题是由于使用单独的连接而出现的。这是你的要求吗?
-
如果您在同一个连接上执行 SELECT 会发生什么?我认为你不会陷入僵局。
-
@Arvo 好的,你有解释为什么会这样吗?
标签: c# sql sql-server