我在一个可以使用SQL或foxpro的C#程序中使用OleDb。我注意到当我在一个带有foxpro数据的事务中运行语句然后尝试调用RollBack时,它不会还原数据。使用SQL数据运行时回滚工作正常,所以我有点困惑为什么它在FoxPro中也不起作用。
在我的测试应用程序中,我正在从表(TESTTABLE)中读取记录到数据表中,该数据表绑定到网格的数据源。我向网格添加行,然后按“保存”按钮清除数据库表,然后遍历绑定的DataTable中的所有当前行,将它们插回到数据库表中。理论上,如果在插入过程中出现问题,RollBack应该撤消删除。我注意到的是,如果插入失败并且我回滚了事务,那么删除的记录将被删除,而不是表格恢复到删除之前的状态。
编辑2013年1月23日
我正在使用Visual FoxPro 9.0.0.5815。表格是loose所以我 创建后必须在桌面上运行“MAKETRANSACTABLE”。我做 这是通过OleDbCommand执行以下命令
string commandText = "ExecScript('Use TESTTABLE In 0'+chr(13)+chr(10)+'MakeTransactable([TESTTABLE])')"
这是我正在使用的保存功能...
private void Save()
{
//Table: TESTTABLE
//Columns: REFERENCE NUMERIC(10), DESCRIPT VARCHAR(20)
bool CauseException = cbBreak.Checked;
//string SQLDbConnString = @"Provider=SQLNCLI;Server=TESTSERVER\\SQLExpress;Database=TESTDATA;Uid=test;Pwd=test;Connect Timeout=600";
string FoxProDbConnString = @"Provider=vfpoledb;Data Source=C:\Test\Data;Exclusive=false;Nulls=false;ConnectTimeOut=600;QueryTimeOut=600;";
using (OleDbConnection dbConn = new OleDbConnection(FoxProDbConnString))
{
dbConn.Open();
using (OleDbTransaction dbTran = dbConn.BeginTransaction())
{
try
{
//Run a delete command to remove all records from the table
string deletequery = "DELETE FROM TESTTABLE";
using (OleDbCommand cmd = new OleDbCommand(deletequery, dbConn, dbTran))
{
cmd.ExecuteNonQuery();
}
//Loop through the DataTable rows and insert them into the database table
foreach (DataRow row in dt.Rows)
{
string insertquery = "INSERT INTO TESTTABLE (REFERENCE, DESCRIPT) VALUES (?,?)";
using (OleDbCommand cmd = new OleDbCommand(insertquery, dbConn, dbTran))
{
if (CauseException)
{
cmd.Parameters.Add("ref", OleDbType.Numeric).Value = "THIS IS NOT A NUMERIC VALUE";
}
else
{
cmd.Parameters.Add("ref", OleDbType.Numeric).Value = Convert.ToDouble(row["reference"]);
}
cmd.Parameters.Add("descript", OleDbType.VarChar).Value = Convert.ToString(row["descript"]).Trim();
cmd.ExecuteNonQuery();
}
}
//If no exceptions were thrown during the inserts, commit the transaction
dbTran.Commit();
MessageBox.Show("Saved");
}
catch (Exception ex)
{
//If an exception occurs, RollBack the transaction. This SHOULD undo the delete.
dbTran.Rollback();
MessageBox.Show("Failed to save. Rolling back changes.");
}
}
}
}
编辑2013年1月24日
我使用System.Data.Odbc而不是上面测试了相同的代码 System.Data.OleDb和交易工作完美。我用了 以下连接字符串:
string odbcConnStr = @“Driver = {INTERSOLV dBASEFile(* .DBF)}; SourceDB = C:\ Test \ Data;”;
在我看来,这里的问题特别针对vfpoledb 提供商没有正确处理交易。另一种我 探索的是使用数据库容器而不是松散的表,但它 似乎vfpoledb不支持“CREATE DATABASE”功能。
答案 0 :(得分:3)
我进行了MakeTransactable
编辑并将其充实。它被称为:
cnn.MakeTransactable("directory/table");
代码:
public static class OleDbConnectionMakeTransactableExtensions
{
private static readonly Dictionary<int, List<string>> AlreadyTransactable = new Dictionary<int, List<string>>();
public static void MakeTransactable(this OleDbConnection connection, string freeTableName)
{
OleDbTransaction tran = connection.GetActiveTransaction();
if (tran == null)
{
throw new InvalidOperationException("No transaction set");
}
int key = tran.GetHashCode();
List<string> transactable;
if (!AlreadyTransactable.TryGetValue(key, out transactable))
{
transactable = new List<string>();
AlreadyTransactable.Add(key, transactable);
}
freeTableName = OtherExtensionMethods.GetCleanTablePath(freeTableName);
if (transactable.Contains(freeTableName, StringComparer.InvariantCultureIgnoreCase))
{
return;
}
string alias = connection.GetCurrentAlias(freeTableName);
if (alias == null)
{
connection.ExecScript(string.Format("use [{0}] shared again in 0", freeTableName));
alias = connection.GetCurrentAlias(freeTableName);
if (alias == null)
{
throw new InvalidOperationException(string.Format("Could not get an alias for table '{0}'", freeTableName));
}
}
connection.ExecScript(string.Format(@"
IF NOT ISTRANSACTABLE('{0}') THEN
MAKETRANSACTABLE('{0}')
ENDIF
", alias));
transactable.Add(freeTableName);
}
public static string GetCurrentAlias(this OleDbConnection connection, string freeTableName)
{
freeTableName = OtherExtensionMethods.GetCleanTablePath(freeTableName);
string alias = connection.ExecScript<string>(string.Format(@"
LOCAL cTable, cAlias, nIndex, nAliasCount, cDbf, cCheck
LOCAL ARRAY aUsedAliases[1]
LOCAL cList
cTable = LOWER(ADDBS(JUSTPATH(""{0}"")) + JUSTSTEM(""{0}""))
nAliasCount = AUSED(""aUsedAliases"")
IF nAliasCount = 0 THEN
RETURN """"
ENDIF
cList = cTable + ': '
FOR nIndex = 1 TO nAliasCount
cAlias = aUsedAliases[1, 1]
cDbf = LOWER(DBF(cAlias))
cCheck = RIGHT(ADDBS(JUSTPATH(cDbf)) + JUSTSTEM(cDbf), LEN(cTable))
cList = cList + ', ' + cAlias + ' -> ' + cDbf + ' -> ' + cCheck
IF cCheck = cTable THEN
RETURN cAlias
ENDIF
ENDFOR
RETURN """"
", freeTableName));
return alias.EmptyToNull();
}
}
public static class OleDbConnectionTransactionExtensions
{
public static OleDbCommand WithTransactionSet(this OleDbCommand command)
{
if (command.Connection == null)
{
throw new InvalidOperationException("Command does not have a Connection set");
}
var transaction = command.Connection.GetActiveTransaction();
if (!Equals(command.Transaction, transaction))
{
command.Transaction = transaction;
}
return command;
}
public static OleDbTransaction GetActiveTransaction(this OleDbConnection connection)
{
if (connection.State != ConnectionState.Open)
{
throw new ArgumentOutOfRangeException("connection", "Connection is not open");
}
return GetTransaction(connection);
}
private static readonly Func<OleDbConnection, OleDbTransaction> GetTransaction;
static OleDbConnectionTransactionExtensions()
{
var getOpenConnectionMethod = typeof(OleDbConnection).GetMethod("GetOpenConnection", BindingFlags.Instance | BindingFlags.NonPublic);
if (getOpenConnectionMethod == null)
{
throw new InvalidOperationException("Could not find the GetOpenConnection() internal method on OleDbConnection");
}
var internalType = getOpenConnectionMethod.ReturnType;
var localTransactionProperty = internalType.GetProperty("LocalTransaction", BindingFlags.Instance | BindingFlags.NonPublic);
if (localTransactionProperty == null)
{
throw new InvalidOperationException("Could not find the LocalTransaction property on OleDbConnectionInternal");
}
var param = Expression.Parameter(typeof(OleDbConnection));
var connection = Expression.Call(param, getOpenConnectionMethod);
var transaction = Expression.Property(connection, localTransactionProperty);
var lambda = Expression.Lambda<Func<OleDbConnection, OleDbTransaction>>(transaction, param);
var compiled = lambda.Compile();
GetTransaction = compiled;
}
}
public static class OtherExtensionMethods
{
public static void ExecScript(this OleDbConnection connection, string script)
{
using (var command = connection.CreateCommand().WithTransactionSet())
{
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "EXECSCRIPT";
command.Parameters.Add(new OleDbParameter("script", script));
command.ExecuteNonQuery();
}
}
public static T ExecScript<T>(this OleDbConnection connection, string script)
{
using (var command = connection.CreateCommand().WithTransactionSet())
{
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "EXECSCRIPT";
command.Parameters.Add(new OleDbParameter("script", script));
object raw = command.Logged().ExecuteScalar();
return ConvertDbResult<T>(raw);
}
}
public static string GetCleanTablePath(string tablePath)
{
return tablePath.ToLower().Replace("/", "\\").Trim("\\"[0]);
}
}
GetActiveTransaction()
和WithTransactionSet()
方法调用使用内部状态从连接中提取活动事务。