连接必须有效且开放 [英] Connection must be valid and open
问题描述
private void ObtenerUsuarios() {
string connString = File.ReadAllText(Application.StartupPath + "\\connectionString.dat");
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
try {
conn.Open();
} catch (Exception ex) {
//MessageBox.Show(ex.Message);
}
MySqlDataReader reader;
command.CommandText = "SELECT * FROM Usuarios";
reader = command.ExecuteReader();
while (reader.Read()) {
Usuario nuevoUsuario = new Usuario();
nuevoUsuario.idUsuario = (int)reader["idUsuario"];
nuevoUsuario.Nombre = reader["Nombre"].ToString();
nuevoUsuario.Fecha = (DateTime)reader["Fecha"];
nuevoUsuario.Foto = reader["Foto"].ToString();
ListaUsuarios.Add(nuevoUsuario);
}
}
我尝试了什么:
我尝试从服务器连接我的sql。
What I have tried:
I try to connect with my sql from server.
推荐答案
不要吞下异常:
Don't "swallow" exceptions:
try {
conn.Open();
} catch (Exception ex) {
//MessageBox.Show(ex.Message);
}
如果连接无法打开 - 而且几乎可以肯定从您显示的错误消息 - 你不知道为什么,甚至它确实失败了!一旦它无法打开,继续使用该方法的其余部分?为什么?您是否认为它仍然有用;即使没有打开它仍然可以工作?
取消注释MessageBox,添加返回
以捕获代码(或更好,将方法的其余部分括在 try
块中,并使用调试器检查连接字符串无法打开时的内容。
顺便说一下:你没有关闭连接,也没有调用Dispose - 所以如果它设法打开,它将锁定数据库文件,直到你的应用程序结束。在数据库组件构造函数周围使用使用
块来确保它们在完成后自动关闭和处理。
If the connection fails to open - and it almost certainly does from the error message you show - you have no idea why, or even that it did fail! And continuing with the rest of the method once it's failed to open? Why? Did you think it woul;d still work, even without it being open?
Uncomment the MessageBox, add a return
to catch code (or better, enclose the rest of the method in the try
block), and use the debugger to examine what is in the connection string when it fails to open.
And by the way: You aren't closing the connection, or calling Dispose on it either - so if it manages to open, it will lock the DB file until your app ends. Use a using
block around DB component constructors to ensure they are automatically Closed and Disposed when you are finished with them.
对不起,问题不清楚。你的conn.Open()是否成功?
您可以尝试以下方式
Sorry, question is not clear. Was your conn.Open() successful ?
You can try in following way
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand myCommand = new MySqlCommand("SELECT * FROM Usuarios");
myCommand.Connection = myConnection;
myConnection.Open();
reader = myCommand.ExecuteReader();
. . .
. . .
. . .
myCommand.Connection.Close();
这篇关于连接必须有效且开放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!