[英]Efficient way to insert a list data into a mySQL database in C#
我有要轉儲到db中的csv文件。 所以我創建了一個文件循環,在循環中我為每行創建了一個名為data的列表
StreamReader file = new StreamReader(itemChecked.ToString());//read the file
while ((line = file.ReadLine()) != null)
{
if (start_flag == true) // start processing the numbers, get the real data
{
List<string> data = new List<string>();
data.AddRange(line.Replace("\"", "").Split(',').AsEnumerable());
}
}
到現在為止還挺好。
現在,我想將列表數據插入數據庫。 列表很大。 我不想像這樣鍵入每個單詞:
insert into table1 (tablenames) values (a, b, c on and on)
如何循環列表並將數據插入數據庫?
首先,您將需要使用MySQL的ADO.NET驅動程序(Connector / NET)連接到數據庫。
其次,您將要打開與數據庫的連接,然后插入一些數據:
var connection = new MySqlConnection();
connection.ConnectionString =
"server=localhost;"
+ "database=DBNAME;"
+ "uid=USERNAME;"
+ "password=PASSWORD;";
connection.Open();
foreach(var datum in data)
{
var command = connection.CreateCommand();
command.CommandText =
"insert into table1 (tablenames)"
+ " values "
+ "(a, b, c on and on)";
var result = command.ExecuteReader();
}
我的示例基於本文 。 這不是一個完美的解決方案,但是它可以幫助您入門。 您可能需要研究MySQL事務,以將插入的內容分為有效的分組(取決於一次的數據大小,可能是100-1000。)
我將使用bulkcopy一次從csv文件導入所有數據。 您可以在此處找到示例:
http://www.codeproject.com/Articles/30705/C-CSV-Import-Export
我希望這是你要找的
問候
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.