Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
连接必须是打开的C#_C#_Mysql - Fatal编程技术网

连接必须是打开的C#

连接必须是打开的C#,c#,mysql,C#,Mysql,这是我的密码 string connString = "Server=localhost;Database=rfid;Uid=root;password=;"; MySqlConnection conn = new MySqlConnection(connString); MySqlCommand command = conn.CreateCommand(); command.CommandText = "Select * from users WHERE id_no = " + this.id

这是我的密码

string connString = "Server=localhost;Database=rfid;Uid=root;password=;";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
command.CommandText = "Select * from users WHERE id_no = " + this.id_no.Text;
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
    label1.Text = "ID Number: " + reader["id_no"].ToString();
    label2.Text = "Name: " + reader["name"].ToString();
    label3.Text = "User type: " + reader["user_type"].ToString();
    id_no.Text = "";
}
它说连接必须是有效的和开放的。
我已经检查了我的防火墙并将其启动。apache和mysql端口正在运行。我的代码中可能出现的错误是什么

您应该将所有IDisposable类放在using语句中,这包括您的连接对象。这样做,包括处理和打开连接:

using (var conn = new SqlConnection(connString))
{
    conn.Open();
    //Do Work
}

您缺少
conn.Open
,并将在执行查询后关闭。@AndrewPaes更好:使用
block@LucasTrzesniewski当然还有更好的方法。我会研究命令参数,并将其包装在一个try-catch中,因为每次有人根据下面的代码更改文本时,您都会触发此命令。肯定是一个using语句,以确保每次调用它时都在清理资源。我还应该提到,您的命令和读取器对象也是IDisposable的,并且是using语句的候选对象。阅读IDisposable和using语句,它真的很方便。