I am trying to use connection pooling on MySQL's .net connector 6.6.4.0 to serve multiple threads using the code below:
static public uint uNonQuery(string query)
{
using (Connection = new MySqlConnection(ConnectionString))
{
if (Connection.State == ConnectionState.Open)
{
Console.WriteLine("Its open..>!!!!");
}
Connection.Open();
MySqlCommand cmd = new MySqlCommand(query, Connection);
cmd.ExecuteNonQuery();
MySqlDataAdapter adapter = new MySqlDataAdapter("SELECT LAST_INSERT_ID() AS 'identity'", Connection);
DataTable dt = new DataTable();
adapter.Fill(dt);
uint ret = 0;
if (dt.Rows.Count > 0)
{
try
{
ret = Convert.ToUInt32(dt.Rows[0]["identity"]);
}
catch
{
ret = 0;
}
}
else
ret = 0;
Connection.Close();
return ret;
}
}
My connection string is
"server = 127.0.0.1; user id = ****; password = ****; database = testdb; pooling=true; maximumpoolsize=500;"
And the thread for testing is
static void DoInserts(object o)
{
int i = (int)o;
Console.WriteLine("Insert Thread {0} launched", i);
for(int x = 0; x < 1000; x++)
{
uint insertId = DataLayer.uNonQuery(String.Format("INSERT INTO testdb.dbtest (writeNo,strNo) VALUES ({0},'x={0} thread={1}')", x, i));
}
Console.WriteLine("Insert Thread {0} completed", i);
}
I get the exception Exception: Connection must be valid and open. after about 6 inserts on 2 concurrent threads, is there something else i need to do enable pooling to work correctly?
Thanks
(Connection.State == ConnectionState.Openindicates there is something wrong with the logic of your code. If you would open the connection in scope, it is no need to check whether it is open already.