【发布时间】:2009-10-22 11:06:52
【问题描述】:
是否可以将 SqlBulkcopy 与 Sql Compact Edition 一起使用,例如(*.sdf) 文件?
我知道它适用于 SQL Server 200 Up,但想检查 CE 兼容性。
如果没有其他人知道在不使用 DataSets 的情况下将 CSV 类型文件导入 SQL Server CE 的最快方法吗?
【问题讨论】:
标签: c# sql-server-ce sqlbulkcopy
是否可以将 SqlBulkcopy 与 Sql Compact Edition 一起使用,例如(*.sdf) 文件?
我知道它适用于 SQL Server 200 Up,但想检查 CE 兼容性。
如果没有其他人知道在不使用 DataSets 的情况下将 CSV 类型文件导入 SQL Server CE 的最快方法吗?
【问题讨论】:
标签: c# sql-server-ce sqlbulkcopy
我这里有一个 SqlCeBulkCopy 库:http://sqlcebulkcopy.codeplex.com - 甚至支持 IEnumerable。
【讨论】:
SQL CE 不支持 BULKCOPY。如果表中有大量行,这是最快的方法;插入太慢了!
using (SqlCeConnection cn = new SqlCeConnection(yourConnectionString))
{
if (cn.State == ConnectionState.Closed)
cn.Open();
using (SqlCeCommand cmd = new SqlCeCommand())
{
cmd.Connection = cn;
cmd.CommandText = "YourTableName";
cmd.CommandType = CommandType.TableDirect;
using (SqlCeResultSet rs = cmd.ExecuteResultSet(ResultSetOptions.Updatable | ResultSetOptions.Scrollable))
{
SqlCeUpdatableRecord record = rs.CreateRecord();
using (var sr = new System.IO.StreamReader(yourTextFilePath))
{
string line;
while ((line = sr.ReadLine()) != null)
{
int index = 0;
string[] values = line.Split('\t');
//write these lines as many times as the number of columns in the table...
record.SetValue(index, values[index++] == "NULL" ? null : values[index - 1]);
record.SetValue(index, values[index++] == "NULL" ? null : values[index - 1]);
record.SetValue(index, values[index++] == "NULL" ? null : values[index - 1]);
rs.Insert(record);
}
}
}
}
}
基准:34370 行的表
插入:每秒写入 38 行
这样:每秒写入 260 行
【讨论】:
这种操作可以增加很多。 为了使这个操作变得有用(我的意思是快速而且相当安全),你可以使用 CE DataAdapter。
通过示例,不关心按键,下面列出的步骤可以帮助您:
将“n”个批处理行从源数据表复制到目标数据表(克隆),执行如下操作:
'... previous codes
For Each currentRow In sourceTable.Rows
'u can do RaiseEvent Processing(currentRow, totalRows) here with DoEvents
If targetTable.Rows.Count < 100 Then
targetTable.InportRow(currentRow)
targetTable.Rows(targetTable.Rows.Count - 1).SetAdded
Else
'...Here you wll call the CE DataAdapter's Update method (da.Update(targetTable))
'...and then be sure you clone the targetTable again, erasing all previous rows.
'...Do a clone again, don't do just a "clear" in the Rows collection.
'...If u have an Autoincrement it will break all Foreign Keys.
End If
Next
'... next codes
通过这种方式,您可以在没有太多时间的情况下更新多行。
我有一些应用程序使用这种方法,在一个包含 5 个 NTEXT 字段(慢)和 800000 行的表中,平均速率约为每秒 1500 行。
当然,这一切都取决于您的表格结构。 IMAGE 和 NTEXT 都是慢速数据类型。
P.S.:正如我所说,这种方法不太关心密钥,所以要小心。
【讨论】:
不,我认为不支持SqlBulkCopy(请参阅MSDN)。也许将数据作为 xml 放入并在服务器上将其剥离? SQL/XML 在 2005/2008 年相当不错。
您可能还想查看 table-value-parameters,但我怀疑 CE 是否支持这些。
【讨论】: