使用 OLEDB 将多条记录导出到 Access 的正确方法
我对使用OLEDB导出数据不太了解,我想到了以下几点:
using (OleDbConnection conn = new OleDbConnection(connString))
{
try
{
conn.Open();
foreach (T t in rows)
{
using( OleDbCommand oleDbCommand = new OleDbCommand(insertString, conn))
{
OleDbParameter param = new OleDbParameter(.., ..);
oleDbCommand.Parameters.Add(param);
//add more parameters
oleDbCommand.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
//handle
}
}
首先,我没有对OleDbCommand使用using语句(即,我没有处理OleDbCommand)。但在这种情况下,即使我完成了导出,记录锁定文件仍保留在数据库中。然而,使用(内部)Using 语句,导出似乎较慢。为什么?如何既能实现快速导出,又能解除导出结束时的记录锁定呢?
I don't know much about exporting data using OLEDB, I figured the following:
using (OleDbConnection conn = new OleDbConnection(connString))
{
try
{
conn.Open();
foreach (T t in rows)
{
using( OleDbCommand oleDbCommand = new OleDbCommand(insertString, conn))
{
OleDbParameter param = new OleDbParameter(.., ..);
oleDbCommand.Parameters.Add(param);
//add more parameters
oleDbCommand.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
//handle
}
}
At first, I didn't use the using statement for the OleDbCommand (i.e., I didn't dispose of the OleDbCommand). But in that case, a record locking file remained on the database even though I was finished exporting. WITH the (inner) Using statement however, exporting seems slower. Why? And how to get both the fast exporting and the removal of the record locking at the end of exporting?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您没有关闭连接,因此当您仍然连接到数据库时,ldb 文件仍然存在。
因此,您应该在连接声明周围放置一条 using 语句(或者在 try 语句的 finally 块中关闭连接 [这正是 using 语句的作用]。
通过 for 循环中的 using 子句,您可以为要插入的每条记录配置 OleDbCommand。但是,您可以为每个插入重复使用 OleDbCommand 实例。 (参见上面的代码)。
接下来,您应该显式启动事务。因为,当您不这样做时,将为每个插入语句创建一个隐式事务。
此外,通过在一个事务中执行所有插入,您将能够在遇到错误时回滚所做的所有更改(插入)。
(例如,如果插入第 159 行失败,您可以回滚之前完成的所有 158 次插入)。
Since you do not close the Connection, the ldb file remains present as you're still connected to the DB.
So, you should put a using statement around the connection-declaration (or close the connection in the finally block of your try statement [which is exactly what the using statement does nb).
With the using clause in the for-loop, you're disposing the OleDbCommand for every record that you're going to insert. However, you can re-use the OleDbCommand instance for every insert. (See code above).
Next to that, you should start a transaction explicitly. Since, when you do not do that, an implicit transaction will be created for each insert statement.
Also, by performing all the inserts inside one transaction, you'll be able to rollback all the changes (inserts) that you've done when you encounter an error.
(For instance, if inserting row nr 159 fails, you can rollback all the 158 inserts that you've done before).