I have a class and my MysqlConnection is in there:
public class DB
{
private static MySqlConnection _Connection;
public static MySqlConnection Connection
{
get
{
if(_Connection == null)
{
string cs = string.Format("SERVER={0}; DATABASE={1}; UID={2}; PWD={3};", SERVER_ADRESS, DATABASE, UID, PWD);
_Connection = new MySqlConnection(cs);
}
if(_Connection.State == System.Data.ConnectionState.Closed)
try
{
MessageBox.Show("MySQL Connection ist geschlossen. Öffne Sie");
_Connection.Open();
}
catch(MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Verbindung zum Server konnte nicht hergestellt werden.");
break;
case 1045:
MessageBox.Show("Ungültiger Benutzername/Passwort.");
break;
default:
MessageBox.Show(ex.Message);
break;
}
}
return _Connection;
}
}
}
So i can use this connection in all the other classes with DB.Connection
.
But now I get "DataReader is already open". But all my DataReader's are in usings.
We start at my login page:
using (loginreader = cmd.ExecuteReader())
{
if (loginreader.Read())
{
DB.Connection.Close();
return true;
}
else
{
DB.Connection.Close();
return false;
}
loginreader.Close();
}
I guess this doesn't work. But the first Error Message after log in i get on another class on line 83:
DataTable schema = null;
using (var schemaCommand = new MySqlCommand("SELECT * FROM " + firmCustomerTablename, connection))
{
using (var reader = schemaCommand.ExecuteReader(CommandBehavior.SchemaOnly))
{
schema = reader.GetSchemaTable();
}
}
which is in a using too. So I don't understand why I get this Error. I guess closing the connections / the DataReaders dont work.
Before this change, i had a connection for every site. But my program had no good performance. So I decided to make 1 connection which is always Open and just call querys to this open connection. And now I get DataReader Errors.
Can someone explain me, why using is not closing the DataReader? And line 83 isn't a DataReader it's a var so i don't know why I get this Error at this line.