Is there any way how to monitor database connection for interruptions? I have one connection shared across applications and some objects should react on connection interruption.
Ideally it should be an event. The only thing I found is a connection exception, but it is raised locally (where I am listening for exceptions).
I have idea to inherit from DbConnection and listen for exception in this object (overloading its methods), raising signal on connection error exception (by related code). But maybe there is simplest way.
Thank you of ideas.
Sharing a single connection is never good and it IS a bad practice. The main reason is actually your problem.
I suggest you change your design a bit (not a big deal) and rely on the ADO.NET connection pooling. It's a must have in case you don't want to run into all kinds of bottlenecks, especially in multithreading situations.
It means that all your connections are transient and you create one only when you need to go to the database.
You can read more about it here, where you can also find samples on how to use it. The main thing to know about it is that it uses the Disposable pattern.
//Notice the **using ** block
using(SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
//do something with the connection.
//as soon as the using block ends, the managed connection is disposed and released in the pool
}
Related
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.
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.
I understand that if I instantiate a SqlConnection object, I am really grabbing a connection from a connection pool. When I call Open(), it will open the connection. If I call the Close() or Dispose() method on that SqlConnection object, it is returned to the connection pool.
However, that doesn't really tell me if it's really closed, or if I still have an active connection to the database.
How can I force a SqlConnection to close at the network level, or at least tell when it closes?
Example:
using(SqlConnection conn = new SqlConnection(DBConnString)) {
conn.Open();
SqlCommand cmd = conn.CreateCommand();
...
cmd.ExecuteReader(CommandBehavior.CloseConnection);
...
}
First run: 300 ms
Second run: 100 ms
Third run: 100 ms
After waiting a long time (30 minutes): 300 ms
If the connection was TRULY closing, the second and third runs should also be 300 ms. But I know that the connection is not truly closed for those runs (I checked the SQL Server's activity monitor). It doesn't take the extra 200ms to perform authentication/etc.
How do I force the connection to truly close?
Ideas
Does CommandBehavior.CloseConnection work? (apparently not?)
Does setting "Max Pool Size = 0" in the connection string work? (this would be a pyrrhic solution)
Does Dispose() work?
References
Article on Connection Pooling
Here's another one that tells us that Close() doesn't really close the connection.
An article on pros and cons connection pooling
Maybe SqlConnection.ClearPool ?
Moe Sisko's answer (Call SqlConnection.ClearPool) is correct.
Sometimes you need a connection to really close rather than return to the pool. As an example, I have a unit test that creates a scratch database, builds the schema, tests some stuff, then drops the scratch database if the tests all pass.
When connection pooling is active, the drop database command fails because there are still active connections. From the point of view of programmer all SQLConnections are closed, but as the pool still holds one open, SQL Server won't allow the drop.
The best documentation for how connection pooling is handled is this page on SQL Server Connection Pooling on MSDN. One doesn't want to turn connection pooling off entirely because it improves performance with repeated opens and closes, but sometimes you need to call a "force close" on an SQLConnection so that it will let go of the database.
This is done with ClearPool. If you call SqlConnection.ClearPool(connection) before closing/disposing, when you do close/dispose it will really go away.
If you don't want to use the connection pool you have to specify it in your SqlConnection.ConnectionString property. For example
"Data Source=MSSQL1;Database=AdventureWorks;Integrated Security=true;Pooling=false;"
Disposing or closing the SqlConnection object is just going to close the connection and return it to the connection pool.
Generally, you want the connection pool to do its job - you don't want the connection to truly close.
Why specifically do you want the connection not to return to the pool?
I see that you are using .net but as this showed up in a google query allow me to give a java response...
Use a DataSource that implements Closeable() and call close on the DataSource. Hikari supports Closeable.
CommandBehavior.CloseConnection is usually discouraged because of this very fact - You can't be sure that the Connection will be closed. (I'll try to find some concrete evidence of this, I'm saying this from faint recall).
Dispose() is the surest way because it implicitly calls Close().
The using construct demonstrated by #Alex is just another (programmer friendly) way of writing the try-finally construct with the added implicit Disposal of objects.
Edit: (after edit to question)
Your concern over the connections actually closing seems unwarranted to me. The connection would simply return to the pool so that it can be reused easily without having to go through all the initialization. This does not mean that the Connection is still actively connected to the DB.
Robert's answer of SqlConnection.ClearPool(TheSqlConn) did exactly what I wanted. It's nice to know the pool CAN be interacted with when necessary.
My use case was: We have ruined a connection and let it go back into the pool, how to we detect that it's ruined and refresh it, so the next user won't have problems.
The solution was: Detect that we have just ruined the connection, and clear it from the pool entirely, letting the pool fill back up with fresh connections.
A decade of writing SqlClient.SqlConnection and I never even thought of interacting with the pool till today.