![](/img/trans.png)
[英]INSERT object or UPDATE if it already exists using BulkCopy (C#, SQL)
[英]Data insert in loop using sql bulkcopy class c#
我現在有兩個數據庫,我必須將一個數據庫中的數據插入到另一個數據庫中。 我知道位sql批量復制,我不知道如何使用sql批量復制一次插入一個數據。
這是我的表結構
CREATE TABLE [CandidateApplication](
[EmailID] [varchar](300) NOT NULL,
[Name] [varchar](300) NULL,
[FileName] [varchar](500) NULL,
[IsDownloaded] [bit] NOT NULL
)
基本上我需要使用IsDownloaded=0
類的子句從一個數據庫中獲取數據,然后我需要循環進行迭代。 在循環中,我將從FileName
字段獲取文件路徑並下載該文件。 如果文件下載成功,那么我必須將數據從db1保存到db2並將字段IsDownloaded=1
更新到db1。
我可以使用sqlbulk復制類通過循環處理從一個數據庫到另一個數據庫的數據插入。 請提出建議。 謝謝
很簡單,伙計:)對不起,我的代碼在VB.net中,希望您不要介意。
注意:重要的是數據表和目標表中的數據類型。 他們應該一樣
碼:
Public Shared Function BulkSave(ByVal dt As DataTable) As Boolean
Dim mydb As New CSdatabase
Try
Dim connectionString = "Connection String"
'' so there is no need to map columns.
Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(connectionString)
bulkCopy.BatchSize = 25000
bulkCopy.BulkCopyTimeout = 300
bulkCopy.ColumnMappings.Add("EmailID", "EmailID")
bulkCopy.ColumnMappings.Add("Name", "Name")
bulkCopy.ColumnMappings.Add("FileName", "FileName")
bulkCopy.ColumnMappings.Add("IsDownloaded", "IsDownloaded")
bulkCopy.DestinationTableName = "dbo.CandidateApplication"
bulkCopy.WriteToServer(dt)
End Using
Catch ex As Exception
Throw ex
Finally
'mydb.closeConnection() ' Close your conneciton here
End Try
Return True
End Function
您無需遍歷一個接一個地插入數據,只需將一個集合傳遞給WriteToServer()方法即可。
一個例子是:
HashSet<SomeObject> dataLines = new HashSet<SomeObject>();
foreach (var entity in someCollection)
{
if(entity == somecondition)
{
dataLines.Add(new SomeObject
{
CollectionItem1 = entity.Property1,
CollectionItem2 = entity.Property2,
CollectionItem3 = entity.Property3,
CollectionItem4 = entity.Property4,
CollectionItem5 = entity.Property5,
CollectionItem6 = entity.Property6,
CollectionItem7 = entity.Property7,
});
}
}
try
{
_context.Connection.Open();
EntityConnection connection = _context.Connection as EntityConnection;
SqlConnection sqlConnection = null;
if (connection != null)
{
sqlConnection = connection.StoreConnection as SqlConnection;
}
if (sqlConnection != null)
{
SqlBulkCopy bulkInsert = new SqlBulkCopy(sqlConnection);
bulkInsert.DestinationTableName = "SomeTable";
bulkInsert.ColumnMappings.Add("CollectionItem1", "Column1");
bulkInsert.ColumnMappings.Add("CollectionItem2", "Column2");
bulkInsert.ColumnMappings.Add("CollectionItem3", "Column3");
bulkInsert.ColumnMappings.Add("CollectionItem4", "Column4");
bulkInsert.ColumnMappings.Add("CollectionItem5", "Column5");
bulkInsert.ColumnMappings.Add("CollectionItem6", "Column6");
bulkInsert.ColumnMappings.Add("CollectionItem7", "Column7");
// dataLines is a collection of objects
bulkInsert.WriteToServer(dataLines.AsDataReader());
_context.SaveChanges();
}
}
finally
{
_context.Connection.Close();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.