【发布时间】:2016-10-24 20:13:39
【问题描述】:
我有一个 csv 文件,我只需要更新我的 sql 数据库表中几列的数据。做这个的最好方式是什么?但是,我在考虑批量导入,如果不使用所有列,它不会让我这样做。我正在考虑使用格式文件,但我想知道这是否是最有效的方法。
这是我在 C# 课程中的尝试方式:
/// <summary>
/// Update all of the PropertyDefinitions
/// </summary>
internal static void InsertPropertyDefinitions()
{
//
// Define the connection
//
SqlConnection insertConnection = null;
try
{
RetryStrategy retryStrategy = new Incremental(5, TimeSpan.FromMilliseconds(500), TimeSpan.FromMilliseconds(3000));
RetryPolicy retryPolicy = new RetryPolicy<SqlDatabaseTransientErrorDetectionStrategy>(retryStrategy);
retryPolicy.ExecuteAction(() =>
{
//
// Try to connect to the database
//
using (insertConnection = new SqlConnection(m_ConnectionString))
{
//
// Open the connection
//
insertConnection.Open();
//
// Get the insert command ready
//
using (SqlCommand insertRecordCmd = insertConnection.CreateCommand())
{
//
// Define the Insert command
//
insertRecordCmd.CommandText = @"
BULK INSERT dbo.[PropertyDefinition]
FROM '//my file path'
WITH(
FIRSTROW = 2,
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
";
// Execute the INSERT command
insertRecordCmd.ExecuteNonQuery();
}
insertConnection.Close();
}
});
}
catch (Exception ex)
{
//
// This is unexpected so display full exception information
//
m_Log.WriteLine("Exception while creating table");
m_Log.WriteLine(ex.Message.ToString());
throw;
}
}
【问题讨论】:
-
批量导入临时表,然后仅使用该表中您需要的列来更新您自己的表。
-
这是一种选择。唯一可能证明困难的是,如果我试图通过重新发布数据库并创建新租户来不断更新此表。
-
所以基本上我会将 csv 文件发送给我们公司的另一个团队。他们会更新一些数据,将文件发回给我,然后我希望能够简单地将这些数据导入到我们当前的表中。
-
为什么不将 CSV 加载到内存中并删除不需要的列。然后使用 SqlBulkCopy。以下 SO 帖子有一个创建 DataTable 和使用 SqlBulkCopy 的示例。您可以修改代码以过滤掉不需要的列。 stackoverflow.com/questions/20759302/…
-
好的,我会试试这个,看看我能不能让它工作。谢谢。
标签: c# sql-server csv