Alex
Alex

Reputation: 398

c# / oracle: open/close connection

I need help with database connections and my winapp.

I have a windows app (C#) that, after I log in, starts running 5 or 6 different queries in Oracle database, every 5-10 seconds. Application is up 24/7.

What is a proper way to do this? Should I open connection during login and never close it until I close the app, or should I open and close connection every time I run a query? For example:

//first query
conn.Open();
DataSet ds1 = new DataSet();

string sql = "SELECT * FROM table1";

OracleCommand cmd = new OracleCommand(sql, conn);
cmd.CommandType = CommandType.Text;
OracleDataAdapter da = new OracleDataAdapter(cmd);
da.Fill(ds1, "Result1");
conn.Dispose();

return ds1;

//second query    
conn.Open();
DataSet ds2 = new DataSet();

string sql = "SELECT * FROM table2";

OracleCommand cmd = new OracleCommand(sql, conn);
cmd.CommandType = CommandType.Text;
OracleDataAdapter da = new OracleDataAdapter(cmd);
da.Fill(ds2, "Result2");
conn.Dispose();

return ds2;

What's the best way to do this?

Upvotes: 1

Views: 2664

Answers (3)

mbarthelemy
mbarthelemy

Reputation: 12913

The Oracle OleDB provider you use in your application implements pooling. So, when you create and clore a connection, you only take/release a connection from a pool of 'real connection'.

This makes creating and disposing Connection objects a really cheap operation. If I were you, I would open a connection, execute my batch of queries, and close+dispose that connection as soon as I'm done and going to sleep (even for a few seconds).

Upvotes: 3

Mutation Person
Mutation Person

Reputation: 30500

Another option, of course is to have a single connection for each 'batch' of queries

However, if you're hitting the database that often then it sounds like you need a permanent connection for the duration of the application.

I asuume of course your sample was just by example, and you are not actaully hitting the database with raw SQL.

Upvotes: 2

Aghilas Yakoub
Aghilas Yakoub

Reputation: 28980

I suggest you to use using block in order to clean your non managed object

using(var connection = new OracleConnection("..."))
{
 .....

}

Nota : Using execute dispose on your object in the end of treatment

Link : http://msdn.microsoft.com/fr-fr/library/yh598w02(v=vs.80).aspx

Upvotes: 1

Related Questions