C# MySQL Query is not working

时间:2016-09-01 06:15:24

标签: c# mysql

Error message is,

Connection must be valid and open.

Is this code wrong? How can i solve the problem?

string strConn = "server = localhost; user = root; database = ****; port = 3306; password = ****; Charset = utf8";
using (MySqlConnection conn = new MySqlConnection(strConn))
{
    MySqlCommand insertCommand = new MySqlCommand();

    conn.Open();

    for (int i = 0; i < 10; i++)
    {
        insertCommand.CommandText = "INSERT INTO master (col_name, col_code)" +
        " SELECT * from (select '" + _name[i] + "', '" + _code[i] + "') as tmp" +
        " WHERE NOT EXISTS (" +
        " SELECT col_code FROM master WHERE col_code = '" + _name[i] + "') limit 1;";

        insertCommand.ExecuteNonQuery();
    }
    conn.Close();
}

2 个答案:

答案 0 :(得分:2)

Before your for loop need to set connection for your CommandObject like:

InsertCommand.Connection = conn;

答案 1 :(得分:1)

您需要使用您创建的连接对象conn为您的命令分配连接。

MySqlCommand insertCommand = conn.CreateCommand();

所以,你的代码是这样的:

string strConn = "server = localhost; user = root; database = ****; port = 3306; password = ****; Charset = utf8";
using (MySqlConnection conn = new MySqlConnection(strConn))
{
    MySqlCommand insertCommand = conn.CreateCommand();

    conn.Open();

    for (int i = 0; i < 10; i++)
    {
        insertCommand.CommandText = "INSERT INTO master (col_name, col_code)" +
        " SELECT * from (select '" + _name[i] + "', '" + _code[i] + "') as tmp" +
        " WHERE NOT EXISTS (" +
        " SELECT col_code FROM master WHERE col_code = '" + _name[i] + "') limit 1;";

        insertCommand.ExecuteNonQuery();
    }
    conn.Close();  //you don't need this.
}

无需通过conn.Close();关闭连接,因为退出using块时连接会自动关闭。

using (MySqlConnection conn = new MySqlConnection(strConn))
{
    //your code
}