Method that I use for handling ExecuteScalar Postgresql queries:
public T ExecuteScalar<T>(string sql, CommandType commandType, List<NpgsqlParameter> parameters)
{
using (NpgsqlConnection conn = Konekcija_na_server.Spajanje("spoji"))
{
return Execute<T>(sql, commandType, c =>
{
var returnValue = c.ExecuteScalar(); //The Connection is not open.
return (returnValue != null && returnValue != DBNull.Value && returnValue is T)
? (T)returnValue
: default(T);
}, parameters);
}
}
"The Connection not open" comment is where it happends, I dont understand why I dont have connection inside, so can someone be so kind to explane me whats happening?
Execute method:
T Execute<T>(string sql, CommandType commandType, Func<NpgsqlCommand, T> function, List<NpgsqlParameter> parameters)
{
using (NpgsqlConnection conn = Konekcija_na_server.Spajanje("spoji"))
using (var cmd = new NpgsqlCommand())
{
cmd.CommandText = sql;
cmd.CommandType = commandType;
if (parameters.Count > 0 )
{
foreach (var parameter in parameters)
{
cmd.Parameters.AddWithValue(parameter.ParameterName,parameter.Value);
}
}
Konekcija_na_server.Spajanje("prekini");
return function(cmd);
}
}
}
My connection class:
class Konekcija_na_server
{
public static string Connectionstring = "Server=127.0.0.1;Port=5433;User Id=postgres;" +
"Password=*********;Database=postgres;Pooling=false;";
public static NpgsqlConnection Spajanje(string konekcija)
{
bool spajanje = false;
NpgsqlConnection conn = new NpgsqlConnection(Connectionstring);
if (konekcija == "spoji")
{
conn.Open();
spajanje = true;
}
else if (konekcija == "prekini")
{
conn.Close();
}
if (spajanje == true)
{
return conn;
}
else return null;
}