App not closing MySql connection properly - c#

I'm having a serious issue with my app. It builds a lot of MySql connections and then it's causing a crash.
I build every method like that:
MySqlConnection connect = new MySqlConnection(
local_connection_string
); //this is global variable.
protected void sample()
{
try
{
connect.Open();
MySqlCommand query = new MySqlCommand(
"here some mysql command"
, connect);
query.ExecuteNonQuery();
}
catch
{
}
finally
{
connect.Dispose();
connect.Close();
}
}
For some reason it's not closing any of these connections and when I keep refreshing it builds connections on the server, once limit is hit app is crashing. All connections are closed when app is shut down.

try this:
using(MySqlConnection conn = new MySqlConnetion(local_connection_string)
{
conn.open();
MySqlCommand query = new MySqlCommand(
"here some mysql command"
, connect);
query.ExecuteNonQuery();
}
using(resource){}: right way for IDisposable resource usage
probably need to add: Application.ApplicationExit event with MySqlConnection.ClearAllPools()

To ensure that connections are always closed, open the connection inside of a using block, as shown in the following code fragment. Doing so ensures that the connection is automatically closed when the code exits the block.
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
// Do work here; connection closed on following line.
}

MySQL counter part uses Connection pooling and does not close when you call close instead it puts it in the connection pool!
Make sure you First Close then Dispose the Reader, Command, and Connection object!
You can use ConnectionString Parameter "Pooling=false" or the static methods MySqlConnection.ClearPool(connection) and MySqlConnection.ClearAllPools()
and Using keyword is the right way to go with this kind of Scenario.

Just close first the connection , before calling the dispose...
finally
{
connect.Close();
connect.Dispose();
}

Related

.NET Core wont close my MySqlConnection

I have a .NET Core program that uses the MySqlConnection class. My Database is a ClearDB Database that is stored in Azure.
When I launch the program it is working like it should. But when I wait for like 10 minuts doing nothing, it wont connect to the database anymore(Timeout?). Restarting the program and it works again.
When looking at the connections on the ClearDB webpage it isn't closing when I close it in my program. After 10 minuts or so it closes automaticly, as I see in ClearDB webpage. But with the program still running it wont connect to the database anymore. Restarting program is only solution.
Code for now looks something like this:
private static async Task<uint> getDeviceId(string macAddress)
{
using (var connection = new MySqlConnection(ConnectionString))
{
uint returnvalue = 0;
var cmd = connection.CreateCommand() as MySqlCommand;
cmd.CommandText = #"SELECT id FROM devices WHERE mac = '" + macAddress + "'";
connection.Open();
Console.WriteLine(connection.State);
DbDataReader reader = await cmd.ExecuteReaderAsync();
using (reader)
{
while (await reader.ReadAsync())
{
returnvalue = await reader.GetFieldValueAsync<uint>(0);
}
}
reader.Dispose();
cmd.Dispose();
return returnvalue;
}
}
I have tried the following:
Using statement
Close/dispose connection,reader and command
Pooling=false in connectionstring
But none of them works. Somebody got an idea?
Assuming MySql provider is like the MSSQL provider, it does not actually close the connection in the database, it just releases it back to the pool.
You do not want to disable pooling, you will kill efficiency.
This is by design, and what you want.
The using statement from the code snippet should close your connections. However, I'm not sure how that interacts with async, or how ClearDB differs from normal MySql. Given the issues in the question and that lack of clarity, you might try this, just to see if it helps:
private static async Task<uint> getDeviceId(string macAddress)
{
uint returnvalue = 0;
MySqlConnection connection;
try
{
connection = new MySqlConnection(ConnectionString);
var cmd = connection.CreateCommand() as MySqlCommand;
//Don't EVER(!) use string concatenation like that in a query!
cmd.CommandText = #"SELECT id FROM devices WHERE mac = #macAddress";
cmd.Parameters.Add("#macAddress", MySqlDbType.VarChar, 18).Value = macAddress;
connection.Open();
Console.WriteLine(connection.State);
DbDataReader reader = await cmd.ExecuteReaderAsync();
using (reader)
{
while (await reader.ReadAsync())
{
returnvalue = await reader.GetFieldValueAsync<uint>(0);
}
}
reader.Dispose();
cmd.Dispose();
}
finally
{
connection.Close();
connection.Dispose();
}
return returnvalue;
}
A using block basically just re-writes your code as try/finally anyway, so doing this step by-hand can sometimes make debugging easier (you can log where it hits the .Close() call).
If this does resolve the problem, I wouldn't stop there, but rather start from there and see just how close to "normal" code you can get. I'm also concerned here that you have disabled connection pooling, and that this method is static.

Get a rid of SqlConnection, which remains in Activity Monitor after being closed/disposed

I'm creating database, using ADO.NET. Basically, I'm executing SQL commands in next way:
private bool ExecuteSqlCommand(string command)
{
var success = true;
using (var connection = GetSqlConnection())
{
if (connection == null)
return false;
using (var myCommand = new SqlCommand("query", connection))
{
try
{
connection.Open();
myCommand.CommandText = command;
myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
success = false;
Log.LogMessage(string.Format("Unable to execute SQL command: {0}", ex.Message));
}
}
}
return success;
}
GetSqlConnection just gets some proper SqlConnection with connection string like
"Server={0}\\{1};User Id={2};Password={3};Application Name={4};"
It works well, and executes command properly, with one exception - according to Sql Manager Studio activity monitor, it remains as active connection even after method was executed.
According to question Why does my SqlConnection remain in the SSMS Processes list after closing it?, this is correct behavior, since connection might be reused. But the serius issue is, that later, READ_COMMITTED_SNAPSHOT command will be called for this database, while using different SqlConnection. Which leads to exception, since READ_COMMITTED_SNAPSHOT requires, that connection, which is used to call this command, should be the only connection to database.
I can't reuse this connection for further operations with database, since I use different connection string for them, with database specified as InitialCatalog (obviously, I can't use it, while database doesn't exist).
So, can I somehow remove this initial connection?
Execute SqlConnection.ClearPool This will mark all connections to be discarded instead of recycled.

Program not responding while connecting to SQL Server

I have a problem. I'm writing window form application in c#.net and connect to SQL Server on Local Network.
if network disconnected my program is not responding. I mean it tries to select data from sql server but network is disconnected. How to catch this error? Thanks in advance.
Check the documentation for timing out MSDN
Here's their example code
using System;
using System.Data.SqlClient;
///
public class A {
///
public static void Main() {
string connectionString = "";
// Wait for 5 second delay in the command
string queryString = "waitfor delay '00:00:05'";
using (SqlConnection connection = new SqlConnection(connectionString)) {
connection.Open();
SqlCommand command = new SqlCommand(queryString, connection);
// Setting command timeout to 1 second
command.CommandTimeout = 1;
try {
command.ExecuteNonQuery();
}
catch (SqlException e) {
Console.WriteLine("Got expected SqlException due to command timeout ");
Console.WriteLine(e);
}
}
}
}
Notice the line
command.CommandTimeout = 1;
Definitely wrap your sql code under the 'using' too, as it will deallocate resources automatically for you.
You basically need to check for the Open Connection First!
SqlConnection con = new SqlConnection(Connection_string); //specify your connection string such as Server database etc ...
if (con.State == System.Data.ConnectionState.Open)
//statements
And you can make an event to Notify that the connection has been closed !

Randomly Getting ExecuteNonQuery requires an open and available connection

I have a loop that runs some ExecuteNonQuery commands. Occasionally it returns the error message:
ExecuteNonQuery requires an open and available connection. The connections
current state is closed.
Here is my code:
private void MyTimerEventHandler(object src, ElapsedEventArgs a)
{
sqlCon = new SqlConnection("server=" + appConfig.sqlServer + ";Trusted_Connection=yes;database=testdb;connection timeout=30;");
sqlCon.Open();
foreach (TagManager tm in tagManagerList)
{
foreach (Tag tag in tm.getTags())
{
SqlCommand insCmd = new SqlCommand("INSERT INTO tag_values (tag_id, value, time) Values (#tagId, #tagValue, #tagTime);", sqlCon);
insCmd.Parameters.Add(new SqlParameter("#tagId", tag.tagNameId));
insCmd.Parameters.Add(new SqlParameter("#tagValue", tag.value));
insCmd.Parameters.Add(new SqlParameter("#tagTime", tag.time));
insCmd.ExecuteNonQuery();
}
}
sqlCon.Close();
}
This code executes in the event handler of a Timer that runs every 15 seconds. The timer is kept alive by GC.KeepAlive() if that makes any difference.
Create a new connection object for each timer callback:
private void MyTimerEventHandler(object src, ElapsedEventArgs a)
{
SqlConnection sqlCon = new SqlConnection( [...]
It is normally a bad idea to reuse a connection. In your case you can run into a race condition if that connection is being used in another thread.
Creating new connections should not affect performance as they are pulled from the Connection pool.
You can check if you connection still open before execute query
if (sqlCon.State == System.Data.ConnectionState.Open)
{
insCmd.ExecuteNonQuery();
}
else
{
sqlCon.Open();
insCmd.ExecuteNonQuery();
}
}
You do not you prepare the insert statement by using the StringBuilder and pass it as text to SQL Command to send once over the SQL SERVER to insert. In this case for all 600 loops , you will need to connect to DB once . Just a thought

How to close connection of Microsoft.Practices.EnterpriseLibrary.Data.ExecuteNonQuery

I'm using the library microsoft.practices.enterpriselibrary, to access a SQL Server database.
I'm wondering how to close connection when I use the ExecuteNonQuery method?
ie:
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
SqlDatabase db = null;
try
{
db = new SqlDatabase(stringConnection);
db.ExecuteNonQuery("storedprocedure", someParams);
}
catch (Exception ex)
{
}
I can't do something like
finally
{
if (db != null)
{
((IDisposable)db).Dispose();
}
}
So... how can I avoid connection leaks?
Thank you.
You can put the code inside the "using" block. This will ensure the connection closed after finishing.
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
SqlDatabase db = new SqlDatabase(stringConnection);
using (DbConnection con = db.CreateConnection())
{
db.ExecuteNonQuery("storedprocedure", someParams);
}
or you can use the con.Close().
Generally you do not need to worry about closing the connection, as Data Access Block manages connections more efficiently. check "Managing Connections" section in below link: http://msdn.microsoft.com/en-us/library/ff953187(v=pandp.50).aspx
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetStoredProcCommand("GetProductsByCategory");
db.AddInParameter(cmd, "#requestId", DbType.Int32, requestId);
db.ExecuteNonQuery(cmd);
The Enterprise Library handles closing connections for you, except for the case of using Data Readers. When using a IDataReader, you should either use the close or a using to call the dispose (same as calling close)
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetSqlStringCommand("Select Name, Address From Customers");
using (IDataReader reader = db.ExecuteReader(cmd))
{
// Process results
}
The dispose in this case will close the connection. They have a great section on connection handling in the documentation.
https://msdn.microsoft.com/en-us/library/ff648933.aspx

Categories