C#连接MySQL抛出System.InvalidOperationException: Connection must be valid and open错误
报错原因及修复方案
核心问题
你创建的MySqlCommand对象没有关联已经打开的数据库连接,命令执行时找不到可用的有效连接,所以抛出该异常。
直接修复方法
给MySqlCommand实例指定Connection属性即可,有两种写法可选:
写法1:创建命令时直接传入连接和SQL语句
// 替换你原来创建MySqlCommand的两行代码 MySqlCommand comm = new MySqlCommand("SELECT * From songs", connection);
写法2:单独给Connection属性赋值
MySqlCommand comm = new MySqlCommand(); comm.CommandText = "SELECT * From songs"; comm.CommandType = System.Data.CommandType.Text; // 新增这一行 comm.Connection = connection;
其他优化建议
- 所有实现了
IDisposable接口的数据库相关对象(MySqlConnection、MySqlCommand、MySqlDataReader)都推荐用using语句包裹,不需要手动调用Close()方法,程序会自动释放资源,哪怕中途出现异常也不会造成连接泄漏。 - 你当前的
catch块只捕获了MySqlException类型的异常,本次抛出的System.InvalidOperationException不会被捕获,建议补充通用异常捕获,或者调整捕获范围。
优化后的完整参考代码
try { string connectionString = "server = 127.0.0.1; user id = root; database = music_db;SSL mode = none;"; using (MySqlConnection connection = new MySqlConnection(connectionString)) { connection.Open(); using (MySqlCommand comm = new MySqlCommand("SELECT * From songs", connection)) { comm.CommandType = System.Data.CommandType.Text; using (MySqlDataReader rd = comm.ExecuteReader()) { string str = "[year]\t[composed]\t[title]\t[album_from]\t[gendreID]" + Environment.NewLine; if (rd.HasRows) { while (rd.Read()) { str += Convert.ToString(rd.GetInt32(0)) + "\t" + rd.GetString(1) + "\t" + rd.GetString(2) + "\t" + rd.GetString(3) + "\t" + rd.GetInt32(4) + Environment.NewLine; } } Console.WriteLine(str); } } } Console.WriteLine("CloseD"); } catch (MySqlException err) { Console.WriteLine("MySQL数据库错误:" + err.Message); } catch (Exception ex) { Console.WriteLine("通用错误:" + ex.Message); }
内容的提问来源于stack exchange,提问作者Mark Mark
相关产品推荐
相关产品推荐

