第二个查询未能更新,因为第一个查询仍在插入过程中
Second query failed to update because first query still in insert progress
private void btnSave_Click(object sender, EventArgs e)
{
using (OleDbConnection con = new OleDbConnection(cs))
{
con.Open();
cmd = new OleDbCommand(“INSERT INTO table1 ([name], [gender], [age]) VALUES ('Jeff', 'Male', 51), con);
cmd.ExecuteNonQuery();
//System.Threading.Thread.Sleep(1000); // it's working if i add a delay here
//int success = cmd.ExecuteNonQuery(); // also working if check number of query affected
//if (success > 0)
//{
// updateLastModified();
//}
updateLastModified();
}
}
public void updateLastModified()
{
using (OleDbConnection con = new OleDbConnection(cs))
{
con.Open();
cmd = new OleDbCommand("UPDATE TABLE1 SET LastModifiedTime='" + DateTime.Now.ToString() + "' WHERE name='Jeff'", con);
cmd.ExecuteNonQuery();
// this was not updated because "Jeff" cannot be found in table1 (first insert query still running)
}
}
我的问题是第二个查询没有更新,因为第一个查询仍然 运行。
除了在执行第二次查询之前“添加延迟”或“检查第一个查询是否成功”之外,还有更好的解决方案吗?
这只是一个示例场景,我不会在一个查询中执行。
更新:
@a.rlx 的建议是使用 OleDbTransaction.Commit 方法。不使用try catch可以这样吗?
using (OleDbConnection con = new OleDbConnection(cs))
{
OleDbTransaction transaction = null;
con.Open();
transaction = con.BeginTransaction();
cmd = new OleDbCommand(“INSERT INTO table1 ([name], [gender], [age]) VALUES ('Jeff', 'Male', 51), con, transaction);
cmd.ExecuteNonQuery();
transaction.Commit();
updateLastModified();
}
您是否尝试过启动事务,运行 两个 SQL 语句,然后提交事务?
private void btnSave_Click(object sender, EventArgs e)
{
using (OleDbConnection con = new OleDbConnection(cs))
{
con.Open();
cmd = new OleDbCommand(“INSERT INTO table1 ([name], [gender], [age]) VALUES ('Jeff', 'Male', 51), con);
cmd.ExecuteNonQuery();
//System.Threading.Thread.Sleep(1000); // it's working if i add a delay here
//int success = cmd.ExecuteNonQuery(); // also working if check number of query affected
//if (success > 0)
//{
// updateLastModified();
//}
updateLastModified();
}
}
public void updateLastModified()
{
using (OleDbConnection con = new OleDbConnection(cs))
{
con.Open();
cmd = new OleDbCommand("UPDATE TABLE1 SET LastModifiedTime='" + DateTime.Now.ToString() + "' WHERE name='Jeff'", con);
cmd.ExecuteNonQuery();
// this was not updated because "Jeff" cannot be found in table1 (first insert query still running)
}
}
我的问题是第二个查询没有更新,因为第一个查询仍然 运行。
除了在执行第二次查询之前“添加延迟”或“检查第一个查询是否成功”之外,还有更好的解决方案吗?
这只是一个示例场景,我不会在一个查询中执行。
更新: @a.rlx 的建议是使用 OleDbTransaction.Commit 方法。不使用try catch可以这样吗?
using (OleDbConnection con = new OleDbConnection(cs))
{
OleDbTransaction transaction = null;
con.Open();
transaction = con.BeginTransaction();
cmd = new OleDbCommand(“INSERT INTO table1 ([name], [gender], [age]) VALUES ('Jeff', 'Male', 51), con, transaction);
cmd.ExecuteNonQuery();
transaction.Commit();
updateLastModified();
}
您是否尝试过启动事务,运行 两个 SQL 语句,然后提交事务?