0

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?

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

ops... very silly mistake on my side. Thanks for pointing this.
Do you mean I should Open, Use and close an Oracle connection everytime the user calls the Service (which could be every 1-2 seconds) and not keep a connection open?
@user2837961: Yes, absolutely. The connection pool will keep it efficient, and you won't need to worry about accidentally using the same connection twice concurrently.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.