[英]How to populate SQL Server database with list of list of objects instead of looping
我有來自Excel電子表格的數據,我無法更改它的輸入方式。是否有一種解決方案,可以將IList<IList<Object>>
值添加到SQL Server數據庫中,而不是因為當前達到5k行的限制而循環。
我還被告知我不應該使用注射劑,因此歡迎其他選擇。
public static void Load_Table()
{
// This function on_click populates the datagrid named JumpTable
// this.JumpTable.ItemsSource = null; // Clears the current datagrid before getting new data
// Pulls in the 2d table from the client sheet
IList<IList<Object>> client_sheet = Get(SetCredentials(), "$placeholder", "Client!A2:AY");
DBFunctions db = new DBFunctions();
db.postDBTable("DELETE FROM Client");
foreach (var row in client_sheet)
{
string exe = "INSERT INTO Client ([Tracker ID],[Request ID]) VALUES('" + row[0].ToString() + "','" + row[1].ToString() + "')";
db.postDBTable(exe);
}
}
數據庫功能
public SqlConnection getDBConnection()
{
// --------------< Function: Opens the connection to our database >-------------- \\
string connectionString = Properties.Settings.Default.connection_string; // Gets the connection source from properties
SqlConnection dbConnection = new SqlConnection(connectionString); // Creates the connection based off our source
if (dbConnection.State != ConnectionState.Open) dbConnection.Open(); // If it's not already open then open the connection
return dbConnection;
}
public DataTable getDBTable(string sqlText)
{
// --------------< Function: Gets the table from our database >-------------- \\
SqlConnection dbConnection = getDBConnection();
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(sqlText, dbConnection);adapter.Fill(table);
return table;
}
public void postDBTable(string sqlText)
{
// --------------< Function: Post data to our database >-------------- \\
SqlConnection dbConnection = getDBConnection();
SqlCommand cmd = new SqlCommand(sqlText, dbConnection);cmd.ExecuteNonQuery();
}
過去,我曾處理過許多批量數據加載。 避免使用SQL Server進行單個插入的主要方法有兩種:一次插入值列表或使用批量插入。
使用值列表的第一個選項是這樣的:
INSERT INTO Foo (Bar,Baz)
VALUES ('bar','baz'),
('anotherbar','anotherbaz')
在c#中,您將遍歷列表並構建值內容,但是在沒有sql注入漏洞的情況下很難做到這一點。
第二個選擇是使用BULK INSERT與SQL批量復制和datatable
。 在進入下面的代碼之前,您將構建一個保存所有數據的DataTable
,然后使用SqlBulkCopy
通過Sql功能插入行,該功能針對插入大量數據進行了優化。
using (var bulk = new SqlBulkCopy(con)
{
//bulk mapping is a SqlBulkCopyColumnMapping[] and is not necessaraly needed if the DataTable matches your destination table exactly
foreach (var i in bulkMapping)
{
bulk.ColumnMappings.Add(i);
}
bulk.DestinationTableName = "MyTable";
bulk.BulkCopyTimeout = 600;
bulk.BatchSize = 5000;
bulk.WriteToServer(someDataTable);
}
這是兩個框架包含的方法。 還有其他可以提供幫助的庫。 Dapper是其中之一,但我不確定它如何處理后端的插入。 實體框架是另一個,但是它只插入一次,因此只是將問題從您的代碼轉移到其他代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.