This might be a very simple question, but more or less, I'm asking to so I can wrap my head around how Data Access blocks opens and closes connections.
First, I have used something like the Enterprise Library for about 10 years, and have switched back and forth between Entities, etc.
Anyway, when I use the CreateDatabase() function of the Database class, does this open a connection immediately to the database OR does it open a connection when I actually make a call using something like ExecuteReader?
How does it handle closing the connection? Do I explicitly have to call the closing of the connection after using it in a DAL? How does Enterprise Library insure the connection is closed after I'm done with the Reader, etc?
Also, what is the best practices for opening and closing the connection IF CreateDatabase opens the connection immediately? Have a small sample of code to share?
CreateDatabase() does not open a connection to the database. The individual commands typically handle the opening and closing of the connection (e.g. ExecuteNonQuery).
Of course there's always an exception. For ExecuteReader, it wouldn't make sense to close the connection immediately. ExecuteReader is set up to close the connection when the DbDataReader is disposed of, which is why you see this pattern using ExecuteReader:
using (IDataReader reader = db.ExecuteReader(cmd))
{
// Process results
}
when the using block is exited, the DbDataReader is disposed of and the connection is closed.
The Enterprise Library Developer's Guide touches on the subject a bit as well.
So, in short, you typically don't have to deal with connection management. The library abstracts that bit of work away and manages it for you.
Related
I'm writing a program that generates Sitemaps. To avoid duplicates I'm using MSSQL Server to store links that are found. during this process It may read and write millions of links and the process of reading and writing may have very little gaps between them (I mean the time between each access to database is very tiny).
I want to know If I can open the connection when the program starts and close it at the end. please consider that creating some sitemaps may take days to finish. Or is it wise to open and close connection each time I want to access the db?
By the way, I'm using sql server locally.
The answer to your question is the Connection Pooling feature.
It is always preferable to open the connection just when needed, access your data, close and dispose the connection immediately
Indeed a specific work pattern exists
using(SqlConnection con = new SqlConnection(.....))
{
... do your work with the database here ....
}
The using statement ensures that the object created at the opening is closed and disposed at the closing braces. Even if an Exception occurs in database code.
This doesn't mean that you cannot try to optimize your code. For example you could gather a few of sitemaps together and write them in just one shot, but usually it is best to follow a simple work pattern, finish the work as soon as possible and worry for optimization later.
You can work with the following code :
SqlConnection conn;
try
{
conn = new SqlConnection(_dbconnstr));
}
catch
{
//exceptions are bubbled
throw;
}
finally
{
//Dispose is always called
conn.Dispose();
}
hope this helps!
I usually open and close connection each time I use it.
Releasing resources must be done when there is many connections around.
If you are the only one, you might keep your resources.
Be aware of setting timeout connection.
Good luck guy!
It is better to open/close the connection. There is no benefits in kipping connection open. ADO.NET Connection pooling (which is on by default) will take care of which connection to close and when.
From MSDN
CAUTION It is recommended that you always close the Connection when
you are finished using it in order for the connection to be returned
to the pool. This can be done using either the Close or Dispose
methods of the Connection object. Connections that are not explicitly
closed might not be added or returned to the pool. For example, a
connection that has gone out of scope but that has not been explicitly
closed will only be returned to the connection pool if the maximum
pool size has been reached and the connection is still valid.
If you know it's going to take a while, what about writing to a local data table and then when you reach a threshold, write all the records to the database.
Or even write the info to a local file (format of your choice) and then write that file to the database in one shot (or multiple shots if you want to do it every x records or y minutes.)
I have question regarding SQL connection open and close.
which one is better:
open connection in form_load event and close it in form_closing event.
open and close connection for each call.
of course sometime I need to read data, frequently.
In general, you should keep database connections open for a small a time as possible.
So, open and close each connection for every call, in a using block to ensure disposal.
I would add that non of this should be happening in the form at all - the form should be concerned with handling UI and UI events - opening and closing connections should happen in you data access layer.
i suggest you would better choose method 2
if you choose 1, may be cause other problems
It depends on how/when you want to use the connection. However you should enable connection pooling which should mitigate opening and closing multiple connections by keeping connections available in a pool for you.
I'd definitely recommend opening and closing the connection on demand. Thanks to connection pooling opening a connection is fairly inexpensive and it means you don't have to deal with checking the connection every time you use it to make sure it is still open.
You should absolutely go for number 2.
Especially in a form, where you don't know for how long the user will occupy the connection.
Remmber to use a Using statement when declaring the connection so you are sure that no matter what happens, the connection will be closed again.
the best practice is to close your sqlconnection as soon as possible so use a sqlconnection with using (it implements an IDisposable interface) as follows:
using (SqlConnection con = new SqlConnection(connectionString))
{
//
// Open the SqlConnection.
//
con.Open();
//do your process
}
I would go for second as the interaction with data base is not required all the time. Usually we load data and save data. Opening connection for long time is useful when there is intense interaction with database and open and closing connection is costly. The code for interaction with database should be separated from UI and should go in data access layer. You can make a separate library of classes which perform database operations or at least make classes for database in the same project.
A general guild line for open connection is to open Open connections
as late as possible and close connections as soon as possible
I work with Windows-Mobile and Windows-CE using SqlCE and I dont know what better to do.
To open connection when the program open, run any query's... update...delete database and close the connection after the program close?
Or open connection run any query's..update...delete database and close the connection immediately?
Nice. The answers are all over the place. Here's what I know from experience and interacting with the SQL Compact team:
Closing the connection flushes the changes you've made, otherwise the engine waits for the flush period before doing it. It's a good idea to close the connection when you're done using it to ensure that your changes actually go to the store. A power loss after a write and before a flush will lose data.
There is no official connection pool, but opening the first connection is expensive (i.e. slow), all others are quick. The recommendation I got from the team is to actually create a connection when the app starts up and just leave it open. You don't actually need to use it, but keeping it open keeps a lot of connection info cached so that subsequent connections to the same store are quick.
So the answer, actually, is both.
Edit
For those interested, a good example of how this works can be seen in the OpenNETCF ORM library. The library, by default, creates a "maintenance" connection that remains open and is used for doing things like schema queries. All other data operations use their own connection. You also have to option to configure the library to reuse a single connection for the life of the Store, or to use a new connection every time it touches the store. Perfomance and behavior has always been best in all of my projects using the default (which is why I made it the default).
Always keep a connection open for the lifetime of your Windows Mobile app. Opening a SQL Server Compact database is a costly operation.
You should close your connection each time you have completed an sql transaction to free connection ports. Always a good practice to avoid security breach.
Connection establishment is a slow operation, so, creating and closing it can slow down the application. On the opposite hand, if you have a lot of clients, the connection pool will be filled very quickly and other clients won't be able to connect.
There are already some conflicting answers here.
To be honest, I'm not enirely sure how WinCE deals with connections. I don't think there is a ConnectionPool.
But the general pattern in .NET is to keep connections open as short as possible. This improves reliability and prevents resource leaks. Make sure you know about the using (var conn = ...) { ... } pattern.
So I would say: go with your second option, and only keep connections longer if you really experience a performance problem, and if opening the connection is the cause. I don't think it will be with SqlCE
On a single-user platform such as wince, there's no harm in keeping the connection open, and you may get better performance.
If worry about data lost because you are not calling Close() frequently, you can execute your code within a transaction that commits changes to disk immediately:
using (SqlCeTransaction transaction = this.connection.BeginTransaction())
{
using (SqlCeCommand command = new SqlCeCommand(query, connection))
{
command.Transaction = transaction;
command.ExecuteNonQuery();
}
transaction.Commit(CommitMode.Immediate);
}
Of course, there is still some performance lost when using CommitMode.Immediate too frequently.
I was wondering if it is a good idea to maintain a database connection ( System.Data.SqlClient.SqlConnection() ) open or is it recommended to close the connection after using it and open it again when needed ? ( Note : My app will run continuously for days/months ) . I am kind of pushed towards leaving it open. Which solution is better ?
In general, dispose of it when you're done with it, and don't worry about it.
ADO.NET implements connection pooling by default, so the connection is kept open behind the scenes so as to spare you the performance penalty of opening new connections all of the time.
Another reason to close the connections in your code -- if you lose connectivity to your database server when you're not using the connection, you won't encounter an error, which could happen if you keep the connection open.
You absolutely should open your connections as late as possible, and close them as soon as possible.
Not only should you close them when you are done, though: you should close them even between closely-related commands, if there is any other code running in between at all. In fact, let me put it like this: Close your ADO.NET Connection objects as quickly and frequently as you practically can. (that is, don't do obviously stupid things to close connections that obviously should not be closed)
By default, the ADO.NET provider for SQL Server (as well as most of the other prominent providers) provide connection pooling. This will actually manage the creation and destruction of these connections for you - but only if you close them when you are done.
If you wrap the creation and use of your connection objects in using blocks, this is easy to do...
using(SqlConnection conn = new SqlConnection(...))
{
///Open and use the connection
} //the 'using' causes it to automatically be closed.
Open the connection if you needed, don't waste resources ;-)
Back to basics.
I have an application written in c# and I am using the sqlClient to connect to database.
I have several methods and I usually open the connection in a try catch block
try{
**open connection**
//Mehod1()
//Method2()
........
}catch(exception){
//Do something
}finally{
**close connection**
}
The Problem is that there are a lot connections in pool.
I am using master page and in master page I am loading the menu from database (different menu for each user).
Then in main pages I open again a connection to get the rest data.
In the middle of the page it may be a method that need again to connect to database.
My Question is
Is this a good practise?
Am I doing something wrong?
Is there a better practise to avoid multiple connections?
What about singleton pattern?
Thanks in advance
SOLUTION
I found the reason!!!
I had forgot to close a connection.
I was sure that I had close it, but
sometimes you can't be so sure.
Thanks everyone for your responses
Since the connection is pooled you don't need to "reuse" it in different methods.
I use the following code:
using(SqlConnection connection = new SqlConnection("your-connectionstring"))
{
// Do your stuff here...
}
Using is just a short hand way of writting try-catch-finally. It is used for disposable objects.
And this can go into each method.
EDIT: Using the connection from the pool is not hurting performance either. All connection information are cached anyway. So just use the SqlConnection on an atomic level.
It's a good thing though to have the ConenctionString handling in a more generic way...
Using() as said above is a good way to new up a new object of a class that implements IDisposable. But with that being said , you cannot leave you connection open once you done. You have finite number of connection in the pool and leaving a connection unclosed can starve other SPIDs which are waiting for active connection which will finally timeout. So you should
Always have atomic and small transactions .
Close when done.
There is DAAB (data access application block) from Microsoft Enterprise Library which can be used as helper to open and close connections + do many other DB related tasks easily. Here it is
http://msdn.microsoft.com/en-us/library/cc511547.aspx
Probably you didn't dispose your SqlConnections
try this:
using (SqlConnection connection = new SqlConnection(connectionString))
{ }
this syntax will call method Dispose() automatically for you. Using statement details here
UPDATE:
A bit more info about this methods you may find here: Close, Dispose
Basically the difference is that method Dispose() called method Close(), but before it is cleaning some resources and removing connection from the pool details here.
As you see Dispose() doing a bit more than Close(). So if you going to reuse connection later use method Close() if not destroy that completely using method Dispose() which is automatically getting called if you using the syntax above.