I am trying to implement a function to close my connection to a database. This function is named "closeDB()" and in the first draft contained one line of code:this.conn.Close();
Afterwards I implemented a simple select to try the database connection, which returned a list of available databases, as seen in this code:
List<string> brokers = new List<string>();
connectToSpecificDB(database);
String query = "SHOW DATABASES LIKE 'pricedata%'";
using var cmd = new MySqlCommand(query, conn);
cmd.Prepare();
using MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
brokers.Add(rdr.GetString(0));
//Console.WriteLine(brokers[brokers.Count - 1]);
}
closeDB();
return brokers;
The line of code that has raised the "System.NullReferenceException" is closeDB();
. If I comment the line, the error does not pop up, however I am not certain if the connector would be available for further connections if it's not closed when I need it to.
After some testing with good old Console.WriteLine, here's the new closeDB() function:
public void closeDB()
{
try
{
if (this.conn.State == ConnectionState.Open)
{
Console.WriteLine("Then close it!");
}
if (this.conn != null && this.conn.State == ConnectionState.Closed)
{
this.conn.Close();
}
else
{
Console.WriteLine("Why the fuck is it null?");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
this.conn.Close();
}
}
The code still raises the exception, mainly due to the finally block, however the output is even more perplexing to me:
Can anyone explain what's going on?