I've got an error in my C# application. I'm not sure if it's my program or my website. It's a gaming emulator and it says after 1-2 hours running 'Too many connections'. It also says it on my website.
The line this code is erroring on is below, and it errors and highlights the words connection.Open(); when it crashes. I think it has something to do with not closing the connections.
//C# Coding (In VB)
private static SqlDatabaseClient CreateClient(int Id)
{
MySqlConnection connection = new MySqlConnection(GenerateConnectionString());
connection.Open();
return new SqlDatabaseClient(Id, connection);
}
//Application error
[04:51] Exception - Session -> To many connection[]MySqlData.MySqlClient.MySqlPacket ReadPacket<> # at MysqlData.MySqlClient.MySqlStream.Readpacket<>
at MySql.Data.MySqlClient.NativeDriver.Open<>
at MySql.Data.MySqlClient.Driver.Open<>
at MySql.Data.MySqlClient.Driver.Create
at MySql.Data.MySqlClient.MySqlPool.GtPooledConnection<>
at MySql.Data.MySqlClient.MySqlPool.TryToGetDriver<>
at MySql.Data.MySqlClient.MySqlPool.GetConnection<>
at MySql.Data.MySqlClient.MySqlConnection.Open<>
at Reality.Storage.SqlDatabaeManager.CreateClient in C:\iRP\SqlDatabaseClient.cs:line 24d
It's good practice to place the code accessing your database within a using clause. By doing this you will ensure that your connections are disposed of when it is not used anymore.
C# Too many connections in MySQL
Take a look at that link. You need to use the 'using' statement so the connections are opened and closed properly.
Related
Some first things that people learned in their early use of MySQL that closing connection right after its usage is important, but why is this so important? Well, if we do it on a website it can save some server resource (as described here) But why we should do that on a .NET desktop application? Does it share the same issues with web application? Or are there others?
If you use connection pooling you won't close the physical connection by calling con.Close, you just tell the pool that this connection can be used. If you call database stuff in a loop you'll get exceptions like "too many open connections" quickly if you don't close them.
Check this:
for (int i = 0; i < 1000; i++)
{
var con = new SqlConnection(Properties.Settings.Default.ConnectionString);
con.Open();
var cmd = new SqlCommand("Select 1", con);
var rd = cmd.ExecuteReader();
while (rd.Read())
Console.WriteLine("{0}) {1}", i, rd.GetInt32(0));
}
One of the possible exceptions:
Timeout expired. The timeout period elapsed prior to obtaining a
connection from the pool. This may have occurred because all pooled
connections were in use and max pool size was reached.
By the way, the same is true for a MySqlConnection.
This is the correct way, use the using statement on all types implementing IDsiposable:
using (var con = new SqlConnection(Properties.Settings.Default.ConnectionString))
{
con.Open();
for (int i = 0; i < 1000; i++)
{
using(var cmd = new SqlCommand("Select 1", con))
using (var rd = cmd.ExecuteReader())
while (rd.Read())
Console.WriteLine("{0}) {1}", i, rd.GetInt32(0));
}
}// no need to close it with the using statement, will be done in connection.Dispose
Yes I think it is important to close out your connection rather than leaving it open or allowing the garbage collector to eventually handle it. There are a couple of reason why you should do this and below that I'll describe the best method for how
WHY:
So you've opened a connection to the database and sent some data back and forth along this pipeline and now have the results you were looking for. Ideally at this point you do something else with the data and the end results of your application is achieved.
Once you have the data from the database you don't need it anymore, its part in this is done so leaving the connection open does nothing but hold up memory and increase the number of connections the database and your application has to keep track of and possibly pushing you closer to your maximum number of connections limit.
"But wait! I have to make a lot of database calls in rapid
succession!"
Okay no problem, open the connection run your calls and then close it out again. Opening a connection to a database in a "modern" application isn't going to cost you a significant amount of computing power/time, while explicitly closing out a connection does nothing but help (frees up memory, lowers your number of current connections).
So that is the why, here is the how
HOW:
So depending on how you are connecting to your MySQL database you a probably using an IDisposible object to help manage the connection. Here is what MSDN has to say on using an IDisposable:
As a rule, when you use an IDisposable object, you should declare and
instantiate it in a using statement. The using statement calls the
Dispose method on the object in the correct way, and (when you use it
as shown earlier) it also causes the object itself to go out of scope
as soon as Dispose is called. Within the using block, the object is
read-only and cannot be modified or reassigned.
Here is my personal take on the subject:
Using a using block helps to keep your code cleaner (readability)
Using a usingblock helps to keep your code clear (memory wise), it will "automagically" clean up unused items
With a usingblock it helps to prevent using a previous connection from being used accidentally as it will automatically close out the connection when you are done with it.
In short, I think it is important to close connections properly, preferably with a con.close() type statement method in combination with a using block
As pointed out in the comments this is also a very good question/answer similar to yours: Why always close Database connection?
This is a bit strange. I have two Oracle databases. One is local. Other is from Amazon. What happens is very weird. I'm using C# to this.
If I open a connection and do some query, it works.
If after 1+ hour I open a connection, It denies it in the first time, then allows it.
When after 1+ hour that I executed the last query in Amazon database, it throws a new OracleException and it just happens in Amazon database. In my local database it leaves me to open a connection anytime, but there it denies it on first time and allows on the second. Also if I use try{} catch() {} it doesn't allows. My current code:
private OracleConnection _oracleConnection = new OracleConnection(ConfigurationManager.ConnectionStrings["Oracle"].ConnectionString);
private void OpenConnection()
{
if (_oracleConnection.State != ConnectionState.Open)
_oracleConnection.Open();
}
public void MyAction(employer)
{
OpenConnection();
using (OracleCommand command = _oracleConnection.CreateCommand())
{
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "proc_0001";
command.Parameters.Clear();
command.Parameters.Add("pi_employer_id, OracleDbType.Int32").Value = employer;
command.ExecuteNonQuery();
}
}
The weird is that if I just execute it in a short time, it goes OK, but if I stay more than 1 hour without to tick Oracle, it throws me an Exception in OpenConnection() and as I'm calling this method in an event of a button click, when I do it again, after the exception, I get my result. I'm starting to think that Oracle is just joking with me. I saw Oracle Documentation and C# Documentation and Connection LifeTime/Connection TimeOut in Oracle's string, but they are to KEEP a connection and I get the error when OPENING a connection, bu as I said, only after a big time and it works fine on second. I don't want to use a workaround to it. Do you know what is the cause of this?
Thanks in advance.
I'm creating an application where I connect to an Access database and do several updates. Since I'm not a database programmer this is also a learning experience. I found the following code online but it didn't work until I added the connection.open() line.
So here's my question. I thought that like in other using cases like creating a file it would automatically open the connection and then dispose at the last }. Why did I have to explicitly call out the open command after creating a new connection?
private static void GetAllTableAndColumnNames(string connectionString)
{
using (OdbcConnection connection =
new OdbcConnection(connectionString))
{
connection.Open();
DataTable tables = connection.GetSchema("Tables");
DataTable columns = connection.GetSchema("Columns");
foreach (DataRow row in columns.Rows)
{
Console.WriteLine(row["COLUMN_NAME"].ToString());
Console.WriteLine(row["TABLE_NAME"].ToString());
}
Console.Read();
}
}
Here's the error I got on runtime without the open command.
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll
Additional information: Invalid operation. The connection is closed.
When the code reaches the end of a using block and it knows that the Connection object is about to be destroyed it "does you a favour" by ensuring that the connection is properly closed. That is because simply destroying the Connection object without notifying the server would be inconsiderate: server connections are often precious commodities and leaving an orphaned connection "open" on the server would be a Bad Thing.
On the other hand, automatically opening a connection when the Connection object is created (i.e., the using statement itself) would not necessarily be a Good Thing. Perhaps you want to create your Connection object, and then create a whole bunch of other objects that depend on the Connection object (e.g., Command, DataAdapter, etc.). Does the connection actually need to be open while that is taking place? If not, then having the connection open for the whole time might also be inconsiderate if you are connecting to a busy server.
Or, to put it another way, there are very legitimate reasons why a Connection object might switch states between "open" and "closed" while it exists, but the only state it should be in at the moment of its demise is "closed". That's why there is the "auto-close" behaviour but not a corresponding "auto-open".
Using clause is designed to close automaticlly resources when the variable is out of scope. The behaviour in the constructor depends on the implementation: DbConnection descendants don't open the conection in the constructor.
I think that this is because constructor overloads: some overloads doesn't take arguments, so can't open the database.
I know this is one of the most popular questions on SO: The Famous "SQL error 26" the difference is that my C# application establishes a connection successfully the first time and then refuses to establish a connection the second time. I restart my computer and the application establishes a connection the first time and then requires a restart again.
The fact that I can establish a connection the first time makes me feel confident that: My server name is correct, My instance name is correct, the username and password combination I use are correct, the server machine is on, the SQL Browser service on the server is running, and I can get through the firewall.
I have a bunch of methods that all look very similar to the following:
private static string connection_string = #"Server=my_server\MS_SQL;User Id=user1;Password=password1"
public static List<string> GetListOfExistingItems(int item_id)
{
List<string> list_items = new List<string>();
try
{
using (SqlConnection sql_conn = new SqlConnection(connection_string))
{
sql_conn.Open();
SqlCommand sql_comm = new SqlCommand("SELECT Name FROM dbo.table1 WHERE ID=" + item_id,
sql_conn);
using (SqlDataReader sql_reader = sql_comm.ExecuteReader())
{
while (sql_reader.Read())
{
list_items.Add(sql_reader["Name"].ToString());
}
sql_reader.Close();
}
}
}
catch (Exception excp)
{
throw new Exception(excp.Message);
}
return list_items;
}
A few interesting facts:
A restart fixes the problem (once).
A log out and log in does NOT fix the problem.
If I do not close the application but instead run the query multiple times, the error does not show up.
I cannot connect to my database from SQL Server Management Studio after I run my application and close it once.
When I restart my computer I see the "Waiting for background programs to close" without any programs being listed. I wait for some time (maybe 10-20 seconds) and the message goes away and the computer eventually restarts.
Thanks in advance.
Somewhere you're not closing your connection.
My next troubleshooting step would be to string-search your code (all of it) for sql_conn.Open();, and find the one(s) not in a using block, or otherwise not getting explicitly closed.
I have a ASP.net based application.
The CPU on the SQL Server box is constantly ~90 - 100%
There are a lot of inneficient queries, which I am currently working on, however, looking at the code from a previous coder, he never seemed to close (or dispose) the SqlConnection
When I run the folloing query, I get around 450 connections that are "Awaiting Command"
SELECT Count(*) FROM
MASTER.DBO.SYSPROCESSES WHERE
DB_NAME(DBID) = 'CroCMS' AND DBID != 0
AND cmd = 'AWAITING COMMAND'
Is this likely to be causing a problem?
I read this and it seems to relate:
http://www.pythian.com/news/1270/sql-server-understanding-and-controlling-connection-pooling-fragmentation/
We are also getting a lot of timeouts, specifically when replication is enabled..
I'm not sure if this is related.. Have disabled replication (transactional) for now and it seems ok..
(This server is a subscriber to our in office Database server)
Would disposing of the SQL connection object help?
Yes, dispose them. Otherwise ignore them for now. Possibly the pool is as large because the statements are slow. I would more suggest:
Fixing the statements.
Check the applicaion that it only uses one connection PER REQUEST (i.e. not open multiple at the same time).
If the problem does not get better after optiomizing SQL - you can revisit the pool.
You should always dispose the command object when your done with it. that way the connection pooling can be used better.
easist is to use the using statment.
using (
var sqlCommand = new SqlCommand(
"storedprocname",
new SqlConnection("connectionstring"))
{ CommandType = CommandType.StoredProcedure })
{
// do what you should.. setting params executing etc etc.
}