使用C#连接MySql

时间:2013-02-19 01:37:58

标签: c# mysql ado.net

我在加载表单中运行此函数,以便在c#中将数据库中的信息显示到dataGridView。问题是表单在尝试访问广告之前弹出检索数据。以下是它在调试器中的运行方式。我运行下面的功能。

public void loadData()
{
    var list = mysql.Select();
    try
    {
        //start from first row
        for (int i = 0; i < dataGridView1.RowCount; i++)
        {
            //insert IDs
            dataGridView1[0, i].Value = list[0][i];
            //insert Names
            dataGridView1[1, i].Value = list[1][i];
            for (int j = 0; j < dataGridView1.ColumnCount; j++)
            {
                if (list[3][j] != null)
                {
                    dataGridView1[j + 2, i].Value = list[3][j];
                }
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

然后它调用mysql类中的Select函数并在MySqlDataReader处停止并弹出Window Form。有人能告诉我什么是在讨价还价吗?

这是Mysql.Select()

public List <string> [] Select()
{
    string query = "SELECT id,name,weekday,description FROM employee e INNER JOIN schedule s ON e.id=s.id";

    //Create a list to store the result
    List<string>[] list = new List<string>[4];
    list[0] = new List<string>();
    list[1] = new List<string>();
    list[2] = new List<string>();
    list[3] = new List<string>();

    //Open connection
    if (this.OpenConnection() == true)
    {
        //Create Command
        MySqlCommand cmd = new MySqlCommand(query, connection);
        //Create a data reader and Execute the command
        MySqlDataReader dataReader = cmd.ExecuteReader();

        //Read the data and store them in the list
        while (dataReader.Read())
        {
            list[0].Add(dataReader["id"] + "");
            list[1].Add(dataReader["name"] + "");
            list[2].Add(dataReader["weekday"] + "");
            list[3].Add(dataReader["description"] + "");
        }

        //close Data Reader
        dataReader.Close();

        //close Connection
        this.CloseConnection();

        //return list to be displayed
        return list;
    }
    else
    {
        return list;
    }
}

1 个答案:

答案 0 :(得分:3)

当它处理MySQL命令并从数据库中获取信息时,应用程序已经有时间绘制表单。

简单修复是这样做的:

    private void frmMain_Load(object sender, EventArgs e)
    {
          this.visible = false;
          loadData();
          this.visible = true;
    }