Click here to Skip to main content
15,898,607 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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);
    }
}


What I have tried:

I try to connect with my sql from server.
Posted
Updated 6-Jun-18 18:50pm

Don't "swallow" exceptions:
C#
try {
        conn.Open();
    } catch (Exception ex) {
        //MessageBox.Show(ex.Message);
    }
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.
 
Share this answer
 
Sorry, question is not clear. Was your conn.Open() successful ?

You can try in following way
C#
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand myCommand = new MySqlCommand("SELECT * FROM Usuarios");
myCommand.Connection = myConnection;
myConnection.Open();
reader = myCommand.ExecuteReader();
 . . .
 . . .
 . . .
myCommand.Connection.Close();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900