Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared SqlConnection

Is it good practice to have one shared SqlConnection object in a .NET application to use for all of your database connections or should you have a separate one each time you access the database?

I currently have a shared one and seem to be running into issues all of a sudden. It seems like I can't use a shared one when I need to use SQL authentication mode instead of Windows authentication mode. I just tried for the first time using SQL authentication and it gave me this error when I tried using the same connection a second time:

There is already an open DataReader associated with this Command which must be closed first.

like image 371
Jeff Stock Avatar asked May 22 '09 21:05

Jeff Stock


People also ask

What is the difference between OleDbConnection and SqlConnection?

SqlConnection is designed to access SQL Server, while OleDbConnection is designed to access any database.

What happens if SqlConnection is not closed?

What happens if SqlConnection is not closed? Not closing connections could cause timeouts as the connection pool may run out of available connections that can be used. A side point to this. If you use the using keyword, that will automatically close the connection for you.

Do I need to open SqlConnection with using?

Yes, you need to Open your connection inside the using block. If you don't explicitly Close() the connection, the end of the using block will do it for you as the using disposes of the connection. When a connection is disposed it is automatically closed.

What is the role of SqlConnection class?

A SqlConnection object represents a unique session to a SQL Server data source. With a client/server database system, it is equivalent to a network connection to the server. SqlConnection is used together with SqlDataAdapter and SqlCommand to increase performance when connecting to a Microsoft SQL Server database.


2 Answers

You should have a separate one really. Reusing connections is handled with connection pooling. The 2nd issue like others have said can probably be resolved by enabling MARS.

like image 130
RichardOD Avatar answered Sep 29 '22 08:09

RichardOD


That error has absolutely nothing to do with authentication. You are reusing a connection from the middle before you closed your SqlDataReader returned from an ExecuteReader(). This is forbidden. You must check your code and eliminate your problem. There are alternatives to use MARS (multiple active record sets) but I would strongly discourage that.

Using multiple connections in your application will probably be even worse because apparently you don't know what connection are in use and when, so when you'll use separate connections you will run into transaction consistency problems.

like image 36
Remus Rusanu Avatar answered Sep 29 '22 10:09

Remus Rusanu