My Dilemma is that I have a method of type MySqlDataReader that executes a query that sent it by parameter and returns the data ... To read this data I must create a Variable of the same type from where the Method is called, until then Well, it works but when I progress in the Project, the server blocks me because I exceed the number of open connections, but if I close the connection in the method, I can not read the data when I invoke the method.
Code:
The Varieble Connection is Declared like this in my Class:
//VARIABLE CONEXION (USADA EN LOS METODOS)
private MySqlConnection Conexion;
And the Method is this:
public MySqlDataReader Consultar(String sql)
{
try
{
//INICIALIZAMOS UNA NUEVA CONEXION CON LOS PARAMETROS DEL CONSTRUCTOR
Conexion = new MySqlConnection(StringConexion.ToString());
//ABRIMOS LA CONEXION
Conexion.Open();
//SE CREA UN COMANDO CON EL SQL OBTENIDO POR PARAMETRO Y LA VARIABLE CONEXION
MySqlCommand Comando = new MySqlCommand(sql, Conexion);
//VARIABLE "Datos" QUE GUARDARA LOS DATOS DE LA BDD AL EJECUTAR EL COMANDO
MySqlDataReader Datos = Comando.ExecuteReader();
//RETORNAMOS LOS DATOS OBTENIDOS DE LA BASE DE DATOS
return Datos;
}
catch (Exception evt)
{
//EN CASO DE ERROR EN LA EJECUCION SE CAPTURA Y SE IMPRIME EL MENSAJE
MessageBox.Show("Error Consultando: " + evt.Message);
//EN CASO DE ERROR EL RETORNO SERA NULO, NO RETORNA DATOS
return null;
}
finally
{
//CERRAMOS LA CONEXION EN CASO DE ERROR
//this.CerrarConex();
}
}
and to read the returned data I must do this:
ClaseBDD Obj_Consulta = new ClaseBDD();
And I read the data like this:
MySqlDataReader datos = Obj_Consulta.Consultar("SELECT * FROM USUARIOS LIMIT 1;");
if(datos.Read()){
//carga de datos ejemplo
TextBox1.Text = datos.GetString(1);
}
If I close the connection in the method, it gives me an error because it does not return anything but if I keep it open, the data load works but it depends on the number of connections because I have many forms where I use this method Any suggestions how can I optimize the method or how can I solve this?