0

我有 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)

如何循环列表并将数据插入数据库?

4

2 回答 2

0

首先,您需要使用ADO.NET Driver for MySQL (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 Transactions以将您的插入批处理成有效的分组(取决于数据大小,一次可能为 100-1000。)

于 2012-04-30T16:48:18.500 回答
0

我会使用 bulkcopy 一次从 csv 文件中导入所有数据。您可以在此处找到示例:

http://www.codeproject.com/Articles/30705/C-CSV-Import-Export

我希望这就是你要找的

问候

于 2012-04-30T16:52:11.043 回答