【MySQL】连接MySQL时出现异常:Connection must be valid and open

今天尝试连接MySQL时出现了一个异常:

未经处理的异常:  System.InvalidOperationException: Connection must be valid and open.
   在 MySql.Data.MySqlClient.MySqlCommand.Throw(Exception ex)
   在 MySql.Data.MySqlClient.MySqlCommand.CheckState()
   在 MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
   在 MySql.Data.MySqlClient.MySqlCommand.ExecuteReader()

【MySQL】连接MySQL时出现异常:Connection must be valid and open_第1张图片

这个异常是说连接必须是有效且开启的,但是奇怪,我明明已经调用了connection.Open()了啊?

经过检查,原来是这一句出现了问题:

MySqlCommand command = new MySqlCommand(commandString);

实际上构造函数中还需要传入MySqlConnection的对象,使用上述只有一个参数的构造方法会出现异常。

正确代码如下:

    string connectString = "Persist Security Info=False;Username=root;Password=123456;" +
                                       "database=MMOG;server=localhost;Connect Timeout=30";
    //  string connectString = "server=localhost;port=3306;user=root;password=123456; database=MMOG;";
    //  string connectString = "Database = MMOG;Data Source=127.0.0.1;port=3306;User Id=root;password=123456;";
    MySqlConnection connection = new MySqlConnection(connectString);
    connection.Open();
    string commandString = "insert into `playerdata`(`username`,`password`) values(@username,@password)";
    MySqlCommand command = new MySqlCommand(commandString,connection);
    command.Parameters.AddWithValue("username", "player1");
    command.Parameters.AddWithValue("password", "player1");
    command.ExecuteReader();

你可能感兴趣的:(学习笔记)