【发布时间】:2014-07-07 23:24:02
【问题描述】:
我正在 TransactionScope 中的 SQL 服务器中进行一些插入操作。
这是我的代码
using (var scope = new TransactionScope(TransactionScopeOption.Required))
{
Int32 existingDBRowCount = GetTableRowCount(currentTableName);
//... Code to Insert Data into Table
Int32 newDBRowCount = GetTableRowCount(currentTableName);
// New Row Count should be equal to Existing DB Row Count + Rows to be inserted
if (newDBRowCount != (existingDBRowCount + toBeInsertedRowCount))
Transaction.Current.Rollback();
else
scope.Complete(); // Commit the Transaction
}
public Int32 GetTableRowCount(string tableName)
{
using (SqlConnection sqlConnection = GetSQLConnection())
{
if (sqlConnection.State != ConnectionState.Open)
sqlConnection.Open();
string queryString = "SELECT COUNT(*) FROM [" + tableName + "]";
using (var sqlCommand = new SqlCommand())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandType = CommandType.Text;
sqlCommand.CommandText = queryString;
var rowCount = (int) sqlCommand.ExecuteScalar();
return rowCount;
}
}
}
基本上我正在做的是跟踪表中的行数,然后在插入新数据后,我检查新行数是否 = 现有行数 + 要插入的行数
如果两者都匹配,我提交事务,否则回滚
我有两个问题:
1) 这种方法正确吗?
2) 在某些情况下,新的 DB Row Counts 与现有行相同,我认为这是因为我的事务直到那时还没有提交,但它是非常随机的,主要是它返回正确的行数.我不知道出了什么问题
【问题讨论】:
-
不,这种方法是不正确的。一切都取决于您在事务内部执行的逻辑。但是您应该能够使用事务隔离级别实现所需的任何同步级别。它们可能会阻止其他事务在您的事务锁定的范围内插入行。在msdn.microsoft.com/en-us//library/ms173763.aspx 阅读更多信息。但不要太严格——这会降低性能。选择将确保逻辑一致性的最低级别
标签: c# sql transactions