1

我有一种将数据插入到MySql数据库中的方法for loop

插入的数量可能很多,所以我的程序在插入过程中会冻结。

所以我想尝试把它放在一个BackgroundWorker,但是它没有按计划工作......

一些插入后,我得到一个异常,我的连接已经打开

这是我的做法:

if (dbPos.connOpen())
{
    // inserts one row, works fine because data is present in db
    dbPos.checkOut(prijs, wie);

    // this works for a few inserts, 
    // but after a couple it will tell me my conn is already open
    worker.RunWorkerAsync(); // inserts many rows
}
dbPos.connClose();

我的BackgroundWorker方法:

void worker_DoWork(object sender, DoWorkEventArgs e)
{
    for (int i = 0; i < chartList.Count; i++)
    {
        switch (this.countChart(i))
        {
            ... Do work ... // insert rows
        }
    }
}

我的方法实际上会将值插入数据库:

using (MySqlCommand cmd = new MySqlCommand(query, conn))
{
    ... parameters ....
    cmd.ExecuteNonQuery();
}

那么我该如何解决这个神秘的问题呢?

4

1 回答 1

4

问题是您正在关闭连接:

if (dbPos.connOpen())
{
    // inserts one row, works fine because data is present in db
    dbPos.checkOut(prijs, wie);

    // This *starts* the work, but doesn't block
    worker.RunWorkerAsync(); // inserts many rows        
}
// This happens while the background work is still occurring
dbPos.connClose();

您应该将dbPos.connOpen()andconnClose()调用移动到BackgroundWorker'DoWork处理程序中。这将允许连接在工作发生时保持打开状态。

于 2013-06-20T16:21:00.663 回答