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;
}
}