I have a ASP.NET (.NET 4.0) application which implements Rest Services. I am connecting to Oracle in this application. My code works fine as under. Please note its in the constructor.
OracleConnection m_cnn = new OracleConnection("Data Source=MySid;User Id=user1;Password=password1");
m_cnn.Open();
//m_connected = ConnectCDB();
Now I change my code as below and I get an null pointer exception
OracleConnection m_cnn = new OracleConnection("Data Source=MySid;User Id=user1;Password=password1");
//m_cnn.Open();
m_connected = ConnectCDB();
The ConnectCDB function is
private bool ConnectCDB()
{
// Open the database connection
m_cnn.Open();
return true;
}
The m_cnn and m_connected are private members of the class. Why should it give error if I call a separate function?
This code:
OracleConnection m_cnn = new OracleConnection("...");
... declares a local variable inside the constructor. It's not assigning a value to the instance variable. To do that, you should use:
m_cnn = new OracleConnection("...");
Having said that, I'd be wary of this pattern anyway - it's generally better to create, open, use and then close connections as and when you need them. It makes it simpler to clean up properly, without implementing IDisposable
all over the place. Rely on the underlying connection pooling to make it efficient.
See more on this question at Stackoverflow