0
I am creating a method to test a connection with the Postgresql database, but when calling the method that opens the connection an error happens saying that the connection is already open and does not work the 'if' for checking the connection status.
Exception : "Connection already open".
public static bool TestaConn()
{
bool Retorno = false;
ConexaoBanco = AbreBD();
if (ConexaoBanco.State == ConnectionState.Open)
{
ConexaoBanco.Close();
Retorno = true;
}
return Retorno;
}
Method that opens connection, the connection string being a global variable:
public static NpgsqlConnection AbreBD()
{
try
{
if (ConexaoBanco.State == ConnectionState.Closed)
{
ConexaoBanco.ConnectionString = ConfGeral.StringConnexaoGeral;
ConexaoBanco.Open();
}
return ConexaoBanco;
}
catch (Exception erro)
{
MessageBox.Show(String.Format("Falha na Tentativa de Acesso a Base de Dados Informada:\n{0}\n \nSE PRECISAR ENTRE EM CONTATO COM NOSSO SUPORTE", erro.Message), "e-SistemIntegra", MessageBoxButtons.OK, MessageBoxIcon.Error);
return ConexaoBanco;
}
}
Put the class code
ConexaoBanco
, please– igventurelli
The database is only a static variable of the type Npgsqlconnection and both the Connected variable and these methods are within the same class. * public class Databaseccess { private Static Npgsqlconnection Conexaobanco = new Npgsqlconnection();
– Victor Freitas
The answer I posted didn’t help?
– igventurelli
No, keep doing the same check.
– Victor Freitas
You want to have no problems with open connections or want to check if the connection is open?
– igventurelli
Both things, I was able to get it working now, but I had to change my connection variable to a local variable in each method, being that before I was trying with a global variable Static;
– Victor Freitas
I get it. I was going to suggest you put the code that gets the return of
AbreBD()
in a blockusing
, then, when leaving the block the connection would be closed. You would ensure that whenever you finish the block the connection would be closed.– igventurelli