2

我有一个分隔文件,用于通过 .net 应用程序在 sql server 表中插入/更新记录。该文件有大约 80000 条记录,每天都会处理。我的问题:在我旋转 80000 行中的每一行时保持与数据库的连接是否安全甚至明智,或者我应该关闭连接并在每次循环迭代时重新打开?这本身听起来很麻烦。但是,我担心长时间保持打开的连接、持有锁和不必要地占用内存。什么是更可扩展、更安全和更明智的方式来做到这一点?

4

2 回答 2

4

First, no you should not open/close the connection every row. For 80,000 rows, that will take forever and will just add to the overhead. You could consider batching the rows (reset the connection say every 10-500 rows). Fortunately, there is a better option:

Secondly, the proper way to insert/update that many rows into a database from a .Net application, is to use the SQLBulkCopy methods, and not the INSERT or UPDATE commands. You should use SQLBulkCopy to load the data rows into a holding/staging table, and then use a SQL Stored Procedure to do the Insert/Update to the actual table(s), en-mass.

If you are concerned about the sustained load of the SQLBulkCopy, it has batching options built-in.

Using this technique, the initial upload of data should be at least 5x faster, and the actual table Insert/Updates should only be a matter of seconds.

于 2013-02-11T20:28:48.840 回答
2

我曾经需要导入数据。但我必须在上面运行一些迷你业务规则。我的要求也是尽可能多地导入行,但如果有任何失败,请记录它(但不要让整个导入失败)。

我写了下面的示例。

http://granadacoder.wordpress.com/2009/01/27/bulk-insert-example-using-an-idatareader-to-strong-dataset-to-sql-server-xml/

我将 N 条记录(例如 N = 1000)作为 ~xml 传递给存储过程。

N 应该是可配置的,以找到“最佳位置”。但是一次一个太慢了,一次80,000个似乎很多。1,000(行)x 80“运行”....是一个很好的起点,恕我直言。

因此,如果您的导入是“哑”的,那么之前建议的“SQLBulkCopy”可能是最好的方法。但是,如果您有任何检查或验证,那么我的示例可能是一个很好的建议。

…………

另外的选择:

http://msdn.microsoft.com/en-us/library/ms162802.aspx bcp.exe

但这并不是真正的“点网代码”。

于 2013-02-11T20:40:22.473 回答