Error connecting to a Mysql database. Object reference not set to an instance of an object

0

What I am trying to do is a simple connection method in c #, but at the moment that I want to make the connection with my Database I get the following error:

  

Reference to object not established as an instance of an object.

Code where I execute the connection methods.

    Base_de_Datos.Conexion conn = new Base_de_Datos.Conexion();
    Base_de_Datos.Conexion myconection = new Base_de_Datos.Conexion();
    connection = conn.iniciarBD();
    aprobar = myconection.OpenConnection();

The connection variable gets all the connection parameters and the approve method obtains whether a connection was established or not. to be able to send various messages.

Method to connect.

    public MySqlConnection iniciarBD()
    {
        server = "localhost";
        database = "presupuesto";
        uid = "root";
        password = "";
        string connectionString;
        connectionString = "SERVER=" + server + ";" + "DATABASE=" +
        database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
        connection = new MySqlConnection(connectionString);
        return connection;

    }

Method to know if I am connected.

    public bool OpenConnection()
    {
        try
        {
            connection.Close();
            connection.Open(); ---- Aqui sale el error
            return true;
        }
        catch (MySqlException ex)
        {
            //When handling errors, you can your application's response based 
            //on the error number.
            //The two most common error numbers when connecting are as follows:
            //0: Cannot connect to server.
            //1045: Invalid user name and/or password.
            switch (ex.Number)
            {
                case 0:
                    MessageBox.Show("No se pudo conectar al servidor. Contacta con el administrador");
                    break;

                case 1045:
                    MessageBox.Show("Contraseña o usario Invalidos, porfavor intentelo de nuevo");
                    break;
            }
            return false;
        }
    }
    
asked by David 23.03.2017 в 19:03
source

1 answer

1

Already locate the Error, it was something very simple to do.

As I used to call my method of iniciarBD() to add its return to a variable and then to the method of OpenConnection() that also needed a Mysql connectivity chain. then just add the method of iniciarBD() , so that the .open method could open something that existed.

        iniciarBD();
        try
        {
            connection.Close();
            connection.Open();
            return true;
        }
    
answered by 23.03.2017 / 19:19
source