It's a bad practice to keep an open connection. I'd advice you to store a connection string and open connection each time within a using block.
public class OleDbGear
{
private readonly string _connectionString;
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="connSrting">Full connSrting to aname="connString">Connection databasestring.</param>
public OleDbGear(string connSrting)
{
_connectionString = connSrting;connString;
}
/// <summary>
/// Returns open connection.
/// </summary>
private OleDbConnection GetOpenConnection()
{
var dbConnection = new OleDbConnection(_connectionString);
dbConnection.Open();
return dbConnection;
}
private T Execute <T>(string query, Action<OleDbCommand> paramsSetup, Func<OleDbCommand, T> func)
{
using (OleDbConnection connection = GetOpenConnection())
using (var cmd = new OleDbCommand(query, connection))
{
if (paramsSetup != null)
paramsSetup(cmd);
return func(cmd);
}
}
public int ExecuteNonQuery(string query, Action<OleDbCommand> paramsSetup = null)
{
return Execute(query, paramsSetup, cmd => cmd.ExecuteNonQuery());
}
public object ExecuteSclar(string query, Action<OleDbCommand> paramsSetup = null)
{
return Execute(query, paramsSetup, cmd => cmd.ExecuteScalar());
}
public T ExecuteReader <T>(string query, Func<OleDbDataReader, T> converter, Action<OleDbCommand> paramsSetup = null)
{
return Execute(query, paramsSetup, cmd =>
{
using (OleDbDataReader reader = cmd.ExecuteReader())
{
if (reader == null)
throw new Exception("DB error");
return converter(reader);
}
});
}
}
Wrapping all in using
blocks ensures correct disposing of all resources. Action<OleDbCommand> paramsSetup
helps you to provide parameters of your query (no injection). Func<OleDbDataReader, T> converter
just converts reader object into usable result.