c# - Reuse of OracleConnection object -
i reuse oracleconnection object more queries wrote simple class:
public static class dbconnectionsmanager { /// <summary> /// /// </summary> private static oracleconnection _dbconnection = null; /// <summary> /// /// </summary> /// <param name="aconnectionstring"></param> /// <returns></returns> public static oracleconnection getdatabaseconnection(string aconnectionstring) { try { if (_dbconnection == null) { _dbconnection = new oracleconnection(aconnectionstring); _dbconnection.open(); return _dbconnection; } if (_dbconnection.state == system.data.connectionstate.closed) { _dbconnection.connectionstring = aconnectionstring; _dbconnection.open(); return _dbconnection; } if (!_dbconnection.connectionstring.equals(aconnectionstring)) { _dbconnection.close(); _dbconnection.connectionstring = aconnectionstring; _dbconnection.open(); return _dbconnection; } return null; } catch (exception e) { return null; } } }
in way can use connection several times:
using (oracleconnection connection = dbconnectionsmanager.getdatabaseconnection(adbconnectionstring)) { oraclecommand command = connection.createcommand(); string sql = "select * mytable"; command.commandtext = sql; oracledatareader reader = command.executereader(); while (reader.read()) { string myfield = (string)reader["example"]; console.writeline(myfield); } }
when call method first time works fine. if recall method static object != null connection result closed! never close connection!
when try reopen connection have exception
.... if (_dbconnection.state == system.data.connectionstate.closed) { _dbconnection.connectionstring = aconnectionstring; _dbconnection.open(); return _dbconnection; } ...
error
message = "cannot access disposed object.\r\nobject name: 'oracleconnection'."
as error says dispose object ...that means need remove using (
clause, clause dispose connection object , y cannot use object outside using (
. means need create new object of calss if want use outside using (
.
you can more idea reading : c# using statement
Comments
Post a Comment