连接必须有效且打开错误

时间:2010-11-20 14:28:11

标签: c# mysql

我收到错误:当我启动此程序时,连接必须有效并打开。我在谷歌搜索,只发现2个人有相同的错误。有可能解决这个问题吗? THX

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Data.Odbc;
using System.Data.Sql;
namespace WindowsFormsApplication1
{
static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        string connectionString = "Server=localhost;Uid=root;Pwd=******;Database=testing;";
        MySql.Data.MySqlClient.MySqlConnection connection = new MySql.Data.MySqlClient.MySqlConnection(connectionString);

        connection.Open();

        string insertQuery = "ALTER TABLE `user` ADD lol INT";
        MySql.Data.MySqlClient.MySqlCommand myCommand = new MySql.Data.MySqlClient.MySqlCommand(insertQuery);
        myCommand.ExecuteNonQuery();
        connection.Close();
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}
}

2 个答案:

答案 0 :(得分:15)

您需要告诉您的命令有关您的连接对象。 将连接参数添加到此行:

MySql.Data.MySqlClient.MySqlCommand myCommand = new MySql.Data.MySqlClient.MySqlCommand(insertQuery, connection);

答案 1 :(得分:4)

您的命令没有分配连接。尝试将连接传递给命令的构造函数,如下所示:

MySql.Data.MySqlClient.MySqlCommand myCommand = new MySql.Data.MySqlClient.MySqlCommand(insertQuery, connection);