/// <summary> /// Clears the connection pool. /// </summary> protected override void ClearPool() { if (Connection != null) { MySqlConnection.ClearPool((MySqlConnection)Connection); } }
/// <summary> /// The MakeDatabaseConnection. /// </summary> /// <param name="logsFile">The logsFile<see cref="StreamWriter"/>.</param> internal static void MakeDatabaseConnection(StreamWriter logsFile) { try { connectionString = ConfigurationManager.ConnectionStrings["qbAgentMySqlDbConnection"].ConnectionString; dbConnection = new MySqlConnection(connectionString); //Console.WriteLine("Database Connection In Progress...\n"); if (dbConnection != null && dbConnection.State == ConnectionState.Closed) { MySqlConnection.ClearPool(dbConnection); dbConnection.Open(); //Console.WriteLine("Database Connected Successfully...\n"); } else { Console.WriteLine("Database Connection Failed, Please Contact Silver Solve...\n"); } } catch (Exception ex) { //StreamWriter logsFile = new StreamWriter("Logs/QB_Agent_" + DateTime.Now.ToString("dd_MM_yyyy") + ".txt", true); Console.WriteLine("Warning Error Occured During Execution, Please Refer to Logs...\n"); logsFile.WriteLine(DateTime.Now + "\tERROR\tError Message:\t" + ex.Message); logsFile.WriteLine(); logsFile.WriteLine(DateTime.Now + "\tERROR\tError Message:\tStack Trace:\t" + ex.StackTrace); logsFile.WriteLine(); } }
private void deleteButton_Click(object sender, EventArgs e) { int ticketId = selectedTicket; int itemId = selectedPartToRemove; if (ticketId == -1 || itemId == -1) { return; } using (MySqlConnection myConn = new MySqlConnection(myConnString)) { //string query = "select * from TechDailyTicket where techId = " + box.SelectedValue + ";"; string query = "DELETE FROM ItemsUsed WHERE ticketId=" + ticketId + " AND itemId=" + itemId + ";"; //always add one for starters Console.WriteLine(query); using (MySqlCommand myComm = new MySqlCommand(query, myConn)) { myComm.Connection.Open(); myComm.ExecuteNonQuery(); myComm.Dispose(); } myConn.Close(); myConn.Dispose(); MySqlConnection.ClearPool(myConn); } MySqlConnection.ClearAllPools(); //refresh the per ticket stuff fillPerTicket(ticketId); }
public Boolean btnConnect() { MainDBInfo.ServerName = settings.serverName; MainDBInfo.DBName = settings.dbName; MainDBInfo.DBPort = settings.dbPort; MainDBInfo.DBUser = settings.userName; MainDBInfo.DBPWD = settings.password; MainDBInfo.ConnectionString = clsDBUtility.CreateConnectionString(MainDBInfo); try { MainDBConne = new MySqlConnection(MainDBInfo.ConnectionString); MainDBConne.Open(); dbCode = clsDBUtility.GetConnectedDatabaseCode(MainDBInfo.ServerName, MainDBInfo.DBName, MainDBInfo.DBPort, MainDBConne, ref errorMessage); LogDBInfo = clsDBUtility.GetLogDBDetails(MainDBConne, dbCode, ref errorMessage); LogDBInfo.DBUser = settings.userName; LogDBInfo.DBPWD = settings.password; clsDBUtility.GetReplicationLogDBInfo(MainDBConne, dbCode, ref errorMessage, ref slaveDatabaseInfo); MySqlConnection.ClearPool(MainDBConne); MainDBConne.Close(); MainDBConne.Dispose(); LogDBInfo.ConnectionString = clsDBUtility.CreateConnectionString(LogDBInfo); LogDBConne = new MySqlConnection(LogDBInfo.ConnectionString); LogDBConne.Open(); } catch (Exception ex) { } return(true); }
private void fillPerTicket(int ticketId) { DataTable ticketTable = new DataTable(); using (MySqlConnection myConn = new MySqlConnection(myConnString)) { //string query = "select * from TechDailyTicket where techId = " + box.SelectedValue + ";"; string query = "SELECT * FROM PerTicket WHERE ticketId=" + ticketId + ";"; //always add one for starters Console.WriteLine(query); using (MySqlCommand myComm = new MySqlCommand(query, myConn)) { MySqlDataAdapter myAdapter = new MySqlDataAdapter(); myAdapter.SelectCommand = myComm; myAdapter.Fill(ticketTable); myComm.Dispose(); } myConn.Close(); myConn.Dispose(); MySqlConnection.ClearPool(myConn); } MySqlConnection.ClearAllPools(); //this.perticketTableAdapter.Fill(ticketTable); this.partsOnTixDisplay.DataSource = ticketTable; resetPartsOnDisplayForRowOne(); }
protected void delete_info(object sender, EventArgs e) { MySqlConnection conn = new MySqlConnection("Data Source= dcm.uhcl.edu;UserId=c563316su01g2;password=2702365;database=c563316su01g2"); try { conn.Open(); if (conn.State == ConnectionState.Open) { conn.Close(); } MySqlCommand cmd = new MySqlCommand(); cmd.Connection = conn; string customerid = (string)Session["customerid"]; cmd.CommandText = "delete from reservation where roomno='" + txt_room.Text + "'&& id='" + customerid + "'"; conn.Open(); int numRowsUpdated = cmd.ExecuteNonQuery(); cmd.Dispose(); Response.Redirect("~/managerhome.aspx"); } catch (Exception exp) { Response.Write(exp); } finally { conn.Close(); conn.Dispose(); MySqlConnection.ClearPool(conn); } }
/// <summary> /// /// </summary> /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { if (disposing && !disposed) { try { cmd.Dispose(); cnn.Dispose(); if (mysqlTrans != null) { mysqlTrans.Dispose(); } } catch { } if (cnn.State == ConnectionState.Open) { cnn.Close(); } if (cnn != null) { MySqlConnection.ClearPool(cnn); } components.Dispose(); } disposed = true; }
private void Aceptar_BajaEquipos_Click(object sender, RoutedEventArgs e) { MySqlConnection BajaDatosCon = new MySqlConnection(Baja_equiposAsist.CadenaConexion()); try { BajaDatosCon.Open(); } catch (Exception ex) { MessageBox.Show($"Se perdio conexion con la base de datos\n\n{ex.Message}"); this.Close(); } if (BajaDatosCon.State == ConnectionState.Open) { try { MySqlDataReader reader = Baja_equiposAsist.In_Baja(BajaDatosCon, CodIn_BajaEquipos.Text, Descripcion_BajaEquipos.Text, Marca_BajaEquipos.Text, Modelo.Text, NumeroSerie.Text, Responsable.Text); reader.Close(); this.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); CodIn_BajaEquipos.Clear(); Marca_BajaEquipos.Clear(); Modelo.Clear(); NumeroSerie.Clear(); Responsable.Clear(); Descripcion_BajaEquipos.Clear(); } } BajaDatosCon.Close(); MySqlConnection.ClearPool(BajaDatosCon); }
/// <summary> /// 执行一个SQL语句,返回DataReader /// </summary> /// <param name="sql">SQL语句</param> /// <param name="cmdType">类型</param> /// <param name="pms">参数</param> /// <returns>DataReader</returns> public static MySqlDataReader ExecuteReader(string connstring, string sql, CommandType cmdType = CommandType.Text, params MySqlParameter[] pms) { MySqlConnection Connection = new MySqlConnection(connstring); MySqlCommand cmd = new MySqlCommand(sql, Connection); cmd.CommandType = CommandType.Text; cmd.CommandTimeout = 10; try { if (Connection.State == ConnectionState.Closed) { Connection.Open(); } if (pms != null) { cmd.Parameters.AddRange(pms); } return(cmd.ExecuteReader(CommandBehavior.CloseConnection)); } catch (Exception ex) { if (Connection.State != ConnectionState.Closed) { MySqlConnection.ClearPool(Connection); Connection.Close(); //Connection.Dispose(); } throw new Exception("自定义:执行时遇到错误", ex); } }
//MÉTODO PARA EDITAR Ó MODIFICAR CATEGORIA EN LA BASE DE DATOS (MYSQL) public bool EditarCategoria(Categoria categoria) { MySqlConnection conexion = ServiciosBD.ObtenerConexion(); try { StringBuilder sentencia = new StringBuilder(); sentencia.AppendLine(" UPDATE CATEGORIA "); sentencia.AppendLine(" SET DESCRIPCION = @NOMBRE "); sentencia.AppendLine(" WHERE ID_CATEGORIA = @CLAVE "); MySqlCommand comando = ServiciosBD.ObtenerComando(conexion, sentencia.ToString()); comando.Parameters.Add(new MySqlParameter("CLAVE", categoria.IdCategoria)); comando.Parameters.Add(new MySqlParameter("NOMBRE", categoria.Descripcion)); comando.CommandText = sentencia.ToString(); return(comando.ExecuteNonQuery() > 0); } catch (Exception ex) { throw new Exception(ex.Message); } finally { conexion.Close(); MySqlConnection.ClearPool(conexion); } }
public override void CloseConnection() { if (connection != null && connection.State != ConnectionState.Closed) { connection.Close(); if (ConType == Connection_Type.File) { Process.Start(new ProcessStartInfo { FileName = "net.exe", Arguments = $"stop MYSQL{port}", Verb = "runas", UseShellExecute = true, WindowStyle = ProcessWindowStyle.Hidden }).WaitForExit(); Process.Start(new ProcessStartInfo { FileName = Directory.GetParent(LocalInstance).Parent.FullName + @"\bin\mysqld.exe", Arguments = $"--remove MYSQL{port}", Verb = "runas", UseShellExecute = true, WindowStyle = ProcessWindowStyle.Hidden }).WaitForExit(); } MySqlConnection.ClearPool(connection as MySqlConnection); } }
public bool EjecutarProcedimiento(string pNombre) { MySqlConnection conexion = ObtenerConexion(); try { MySqlCommand cmdProc = new MySqlCommand(pNombre, conexion); cmdProc.CommandType = CommandType.StoredProcedure; if (conexion.State != ConnectionState.Open) { conexion.Open(); } cmdProc.ExecuteNonQuery(); return(true); } catch (Exception ex) { throw ex; } finally { conexion.Close(); MySqlConnection.ClearPool(conexion); } }
public void FillFromStoredProcedureMultipleTimesCreatesExpectedRows() { executeSQL("CREATE PROCEDURE SimpleSelect() BEGIN SELECT 'ADummyVal' as DummyVal; END"); MySqlConnectionStringBuilder cb = new MySqlConnectionStringBuilder(ConnectionSettings.ConnectionString); cb.Pooling = true; using (MySqlConnection connection = new MySqlConnection(cb.ConnectionString)) { MySqlDataAdapter adapter = new MySqlDataAdapter("SimpleSelect", connection); adapter.SelectCommand.CommandType = CommandType.StoredProcedure; DataTable table = new DataTable(); adapter.Fill(table); Assert.Equal(1, table.Rows.Count); adapter = new MySqlDataAdapter("SimpleSelect", connection); adapter.SelectCommand.CommandType = CommandType.StoredProcedure; table = new DataTable(); adapter.Fill(table); Assert.Equal(1, table.Rows.Count); MySqlConnection.ClearPool(connection); } }
public Boolean initReplicate() { testMail.fromID = "*****@*****.**"; testMail.fromPass = "******"; testMail.toID = "*****@*****.**"; clsStatus.UdpateStatusText("Loading Application...\r\n"); System.Threading.Thread.Sleep(500); replicationQueue = new System.Collections.Queue(); if (string.IsNullOrEmpty(settings.serverName)) { clsStatus.UdpateStatusText("Invalid Setting\r\n"); return(false); } MainDBInfo.ServerName = settings.serverName; MainDBInfo.DBName = settings.dbName; MainDBInfo.DBPort = settings.dbPort; MainDBInfo.DBUser = settings.userName; MainDBInfo.DBPWD = settings.password; MainDBInfo.ConnectionString = clsDBUtility.CreateConnectionString(MainDBInfo); try { clsStatus.ClearStatusText(); clsStatus.UdpateStatusText("Connecting to Master Database...\r\n"); System.Threading.Thread.Sleep(500); MainDBConn = new MySqlConnection(MainDBInfo.ConnectionString); MainDBConn.Open(); dbCode = clsDBUtility.GetConnectedDatabaseCode(MainDBInfo.ServerName, MainDBInfo.DBName, MainDBInfo.DBPort, MainDBConn, ref errorMessage); if (dbCode == null) { clsStatus.UdpateStatusText("Unable to locate current database from the list\r\n"); System.Threading.Thread.Sleep(500); return(false); } clsStatus.UdpateStatusText("Successfully Connected to Master Database\r\n"); System.Threading.Thread.Sleep(500); clsStatus.UdpateStatusText("Fetching data from Master Database\r\n"); System.Threading.Thread.Sleep(500); LogDBInfo = clsDBUtility.GetLogDBDetails(MainDBConn, dbCode, ref errorMessage); LogDBInfo.DBUser = settings.userName; LogDBInfo.DBPWD = settings.password; clsDBUtility.GetReplicationLogDBInfo(MainDBConn, dbCode, ref errorMessage, ref slaveDatabaseInfo); clsStatus.UdpateStatusText("Closing Master Database Connection...\r\n"); System.Threading.Thread.Sleep(500); MySqlConnection.ClearPool(MainDBConn); MainDBConn.Close(); MainDBConn.Dispose(); clsStatus.UdpateStatusText("Successfully Closed Master Database Connection.\r\n\r\n\r\n"); System.Threading.Thread.Sleep(500); LogDBInfo.ConnectionString = clsDBUtility.CreateConnectionString(LogDBInfo); } catch (MySqlException sqlEx) { clsStatus.UdpateStatusText(sqlEx.Message + "\n\r\n\r"); return(false); } return(true); }
// MÉTODO PARA OBTENER TODAS LAS CATEGORIAS EN LA BASE DE DATOS (MYSQL) public ListaCategoria ObteberCategoria() { ListaCategoria lista = new ListaCategoria(); MySqlConnection conexion = ServiciosBD.ObtenerConexion(); try { StringBuilder sentencia = new StringBuilder(" SELECT *FROM CATEGORIA "); MySqlCommand comando = ServiciosBD.ObtenerComando(conexion, sentencia.ToString()); comando.CommandText = sentencia.ToString(); MySqlDataReader lector = comando.ExecuteReader(); while (lector.Read()) { Categoria entidad = ConvertEntity(lector); lista.Add(entidad); } lector.Close(); } catch (Exception ex) { throw new Exception(ex.Message); } finally { conexion.Close(); MySqlConnection.ClearPool(conexion); } return(lista); }
//ELIMINAR CATEGORIA MEDIANTE LA CLAVE DESDE LA BASE DE DATOS (MYSLQ) public bool EliminarCategoria(string clave) { MySqlConnection conexion = ServiciosBD.ObtenerConexion(); try { StringBuilder sentencia = new StringBuilder(); sentencia.AppendLine(" DELETE FROM CATEGORIA WHERE ID_CATEGORIA = @CLAVE "); MySqlCommand comando = ServiciosBD.ObtenerComando(conexion, sentencia.ToString()); comando.Parameters.Add(new MySqlParameter("CLAVE", clave)); comando.CommandText = sentencia.ToString(); return(comando.ExecuteNonQuery() > 0); } catch (Exception ex) { throw new Exception(ex.Message); } finally { conexion.Close(); MySqlConnection.ClearPool(conexion); } }
public void ChangeStoredProcedureBasedSelectCommandDoesNotThrow() { executeSQL("CREATE PROCEDURE SimpleSelect1() BEGIN SELECT 'ADummyVal' as DummyVal; END"); executeSQL("CREATE PROCEDURE SimpleSelect2() BEGIN SELECT 'ADummyVal' as DummyVal; END"); MySqlConnectionStringBuilder cb = new MySqlConnectionStringBuilder(ConnectionSettings.ConnectionString); cb.Pooling = true; using (MySqlConnection connection = new MySqlConnection(cb.ConnectionString)) { MySqlDataAdapter adapter = new MySqlDataAdapter("SimpleSelect1", connection); adapter.SelectCommand.CommandType = CommandType.StoredProcedure; DataTable table = new DataTable(); adapter.Fill(table); Assert.Equal(1, table.Rows.Count); adapter.SelectCommand = new MySqlCommand("SimpleSelect2", connection); adapter.SelectCommand.CommandType = CommandType.StoredProcedure; table = new DataTable(); try { adapter.Fill(table); Assert.Equal(1, table.Rows.Count); } finally { MySqlConnection.ClearPool(connection); } } }
public RoomInfo getRoomInfoById(int roomId) { string query = "SELECT room.id, room.roomNumber, rt.roomType " + "FROM sad2_db.room_type rt " + "INNER JOIN sad2_db.room room " + "ON rt.id = room.roomTypeId " + "WHERE room.id = @roomId"; using (MySqlCommand cmd = new MySqlCommand(query, conn)) { MySqlDataReader myReader; conn.Open(); cmd.Parameters.AddWithValue("@roomId", roomId); using (myReader = cmd.ExecuteReader()) { if (myReader.Read()) { return(new RoomInfo { RoomId = (myReader[0]).ToString(), RoomNumber = myReader[1].ToString(), RoomType = (myReader[2]).ToString() }); } MySqlConnection.ClearPool(conn); } MySqlConnection.ClearPool(conn); } MySqlConnection.ClearPool(conn); return(null); }
public void ChangeStoredProcedureBasedSelectCommandDoesNotThrow() { execSQL("CREATE PROCEDURE SimpleSelect1() BEGIN SELECT 'ADummyVal' as DummyVal; END"); execSQL("CREATE PROCEDURE SimpleSelect2() BEGIN SELECT 'ADummyVal' as DummyVal; END"); using (MySqlConnection connection = new MySqlConnection(GetPoolingConnectionString())) { MySqlDataAdapter adapter = new MySqlDataAdapter("SimpleSelect1", connection); adapter.SelectCommand.CommandType = CommandType.StoredProcedure; DataTable table = new DataTable(); adapter.Fill(table); Assert.AreEqual(1, table.Rows.Count); adapter.SelectCommand = new MySqlCommand("SimpleSelect2", connection); adapter.SelectCommand.CommandType = CommandType.StoredProcedure; table = new DataTable(); try { Assert.DoesNotThrow(delegate { adapter.Fill(table); }); Assert.AreEqual(1, table.Rows.Count); } finally { MySqlConnection.ClearPool(connection); } } }
public override void Dispose() { switch (Enum.Parse <MixEnums.DatabaseProvider>(MixService.GetConfig <string>("DatabaseProvider"))) { case 0: { SqlConnection.ClearPool((SqlConnection)RelationalDatabaseFacadeExtensions.GetDbConnection(this.get_Database())); break; } case 1: { MySqlConnection.ClearPool((MySqlConnection)RelationalDatabaseFacadeExtensions.GetDbConnection(this.get_Database())); break; } case 2: { NpgsqlConnection.ClearPool((NpgsqlConnection)RelationalDatabaseFacadeExtensions.GetDbConnection(this.get_Database())); break; } } this.Dispose(); return; }
public bool InsertarSubCategoria(SubCategoria entidad) { MySqlConnection conexion = ServiciosBD.ObtenerConexion(); try { StringBuilder sentencia = new StringBuilder(" INSERT INTO SUBCATEGORIA ( ID_CATEGORIA, ID_SUBCATEGORIA, DESCRIPCION) "); sentencia.AppendLine(" VALUES ( @ID_CATEGORIA, @ID_SUBCATEGORIA, @DESCRIPCION ) "); MySqlCommand comando = ServiciosBD.ObtenerComando(conexion, sentencia.ToString()); comando.Parameters.Add(new MySqlParameter("ID_CATEGORIA", entidad.IdCategoria)); comando.Parameters.Add(new MySqlParameter("ID_SUBCATEGORIA", entidad.IdSubCategoria)); comando.Parameters.Add(new MySqlParameter("DESCRIPCION", entidad.Descripcion)); return(comando.ExecuteNonQuery() > 0); } catch (Exception ex) { throw new Exception(ex.Message); } finally { conexion.Close(); MySqlConnection.ClearPool(conexion); conexion.Dispose(); } }
protected void update_info(object sender, EventArgs e) { MySqlConnection conn = new MySqlConnection("Data Source= dcm.uhcl.edu;UserId=c563317fa02g6;password=2570800;database=c563317fa02g6"); try { conn.Open(); if (conn.State == ConnectionState.Open) { conn.Close(); } MySqlCommand cmd = new MySqlCommand(); cmd.Connection = conn; string customerid = (string)Session["customerid"]; cmd.CommandText = "update reservation set customername='" + txt_name.Text + "',cardtype='" + txt_ctype.Text + "',cardno='" + txt_card.Text + "',cvv='" + txt_cvv.Text + "',phonenumber='" + txt_number.Text + "' where roomno='" + txt_room.Text + "' && id='" + customerid + "'"; conn.Open(); int numRowsUpdated = cmd.ExecuteNonQuery(); cmd.Dispose(); Response.Redirect("~/managerhome.aspx"); } catch (Exception exp) { Response.Write(exp); } finally { conn.Close(); conn.Dispose(); MySqlConnection.ClearPool(conn); } }
protected void GridView_deleted_Row(object sender, GridViewSelectEventArgs e) { MySqlConnection conn = new MySqlConnection("Data Source= dcm.uhcl.edu;UserId=c563317fa02g6;password=2570800;database=c563317fa02g6"); try { conn.Open(); if (conn.State == ConnectionState.Open) { conn.Close(); } MySqlCommand cmd = new MySqlCommand(); string roomnumber = GridView2.Rows[e.NewSelectedIndex].Cells[1].Text; cmd.Connection = conn; cmd.CommandText = "update room set checkindate=null,checkoutdate=null,customername=null,occupancy=0 where roomno='" + roomnumber + "'"; conn.Open(); int numRowsUpdated = cmd.ExecuteNonQuery(); cmd.Dispose(); Response.Redirect("~/managerhome.aspx"); } catch (Exception exp) { Response.Write(exp); } finally { conn.Close(); conn.Dispose(); MySqlConnection.ClearPool(conn); } }
private void button1_Click(object sender, EventArgs e) { // Ein neues Schießjahr soll in der Datenbank angelegt werden MySqlConnection conn = new MySqlConnection(Properties.Settings.Default.siusclubConnectionString); try { conn.Open(); if (SchiessjahrTextbox.Text.Length != 0) { MySqlCommand cmd = new MySqlCommand("INSERT INTO schiessjahr (Schiessjahr, SchiessjahrBeginn) VALUES (@Schiessjahr, @SchiessjahrBeginn)", conn); cmd.Prepare(); cmd.Parameters.Add("@Schiessjahr", MySqlDbType.VarChar, 45).Value = SchiessjahrTextbox.Text; cmd.Parameters.Add("@SchiessjahrBeginn", MySqlDbType.Date).Value = SchiessjahrBeginn.Value.Date; cmd.ExecuteNonQuery(); } conn.Close(); conn.Dispose(); MySqlConnection.ClearPool(conn); Close(); } catch (MySqlException mysqle) { MessageBox.Show("Ein Fehler ist aufgetreten beim Anlegen eines neuen Schießjahres (" + mysqle.Message + ")."); } }
public override void Create() { using (var workingConnection = _connection.CreateSystemConnection()) { _migrationCommandExecutor.ExecuteNonQuery(GetCreateOps(), workingConnection); MySqlConnection.ClearPool((MySqlConnection)_connection.DbConnection); } }
public void ClearPool() { if (this.connection != null) { MySqlConnection.ClearPool(this.connection); this.Release(); } }
public void ClearPool() { string connStr = GetPoolingConnectionString() + ";min pool size=10"; MySqlConnectionStringBuilder settings = new MySqlConnectionStringBuilder(connStr); MySqlConnection[] connections = new MySqlConnection[10]; connections[0] = new MySqlConnection(connStr); connections[0].Open(); string assemblyName = typeof(MySqlConnection).GetTypeInfo().Assembly.FullName; string pmName = String.Format("MySql.Data.MySqlClient.MySqlPoolManager, {0}", assemblyName); Type poolManager = Type.GetType(pmName, false); FieldInfo poolManagerHashTable = poolManager.GetField("pools", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance); Hashtable poolHash = (Hashtable)poolManagerHashTable.GetValue(null); FieldInfo clearingPoolsFI = poolManager.GetField("clearingPools", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance); ICollection clearingPools = (ICollection)clearingPoolsFI.GetValue(null); // now we need to investigate string poolName = String.Format("MySql.Data.MySqlClient.MySqlPool, {0}", assemblyName); Type poolType = Type.GetType(poolName, false); FieldInfo inUsePool = poolType.GetField("inUsePool", BindingFlags.NonPublic | BindingFlags.Instance); ICollection inUseList = (ICollection)inUsePool.GetValue(poolHash[settings.ConnectionString]); Assert.AreEqual(1, inUseList.Count); FieldInfo idlePool = poolType.GetField("idlePool", BindingFlags.NonPublic | BindingFlags.Instance); ICollection idleList = (ICollection)idlePool.GetValue(poolHash[settings.ConnectionString]); Assert.AreEqual(9, idleList.Count); // now open 4 more of these. Now we shoudl have 5 open and five // still in the pool for (int i = 1; i < 5; i++) { connections[i] = new MySqlConnection(connStr); connections[i].Open(); } Assert.AreEqual(5, inUseList.Count); Assert.AreEqual(5, idleList.Count); Assert.AreEqual(0, clearingPools.Count); // now tell this connection to clear its pool MySqlConnection.ClearPool(connections[0]); Assert.AreEqual(1, clearingPools.Count); Assert.AreEqual(0, idleList.Count); for (int i = 0; i < 5; i++) { connections[i].Close(); } Assert.AreEqual(0, clearingPools.Count); }
public override async Task CreateAsync(CancellationToken cancellationToken = default(CancellationToken)) { using (var workingConnection = _connection.CreateSystemConnection()) { await _migrationCommandExecutor.ExecuteNonQueryAsync(GetCreateOps(), workingConnection, cancellationToken); MySqlConnection.ClearPool((MySqlConnection)_connection.DbConnection); } }
private void ClearConnectionPoolIfDatabaseFailingOver( MySqlException ex) { if (ex.IsFailoverException()) { MySqlConnection.ClearPool( new MySqlConnection(GetConnectionString())); } }
public void ClearPool() { // Start by clearing clearingPools for a clean test List <MySqlPool> clearingPools = GetClearingPools(); clearingPools.Clear(); string connStr = GetPoolingConnectionString() + ";min pool size=10"; MySqlConnectionStringBuilder settings = new MySqlConnectionStringBuilder(connStr); MySqlConnection[] connections = new MySqlConnection[10]; connections[0] = new MySqlConnection(connStr); connections[0].Open(); Type poolManagerType = typeof(MySqlPoolManager); FieldInfo poolManagerHashTable = poolManagerType.GetField("pools", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance); Dictionary <string, MySqlPool> poolHash = (Dictionary <string, MySqlPool>)poolManagerHashTable.GetValue(null); // now we need to investigate Type poolType = typeof(MySqlPool); FieldInfo inUsePool = poolType.GetField("inUsePool", BindingFlags.NonPublic | BindingFlags.Instance); ICollection inUseList = (ICollection)inUsePool.GetValue(poolHash[settings.ConnectionString]); Assert.AreEqual(1, inUseList.Count); FieldInfo idlePool = poolType.GetField("idlePool", BindingFlags.NonPublic | BindingFlags.Instance); ICollection idleList = (ICollection)idlePool.GetValue(poolHash[settings.ConnectionString]); Assert.AreEqual(9, idleList.Count); // now open 4 more of these. Now we shoudl have 5 open and five // still in the pool for (int i = 1; i < 5; i++) { connections[i] = new MySqlConnection(connStr); connections[i].Open(); } Assert.AreEqual(5, inUseList.Count); Assert.AreEqual(5, idleList.Count); clearingPools = GetClearingPools(); Assert.AreEqual(0, clearingPools.Count); // now tell this connection to clear its pool MySqlConnection.ClearPool(connections[0]); Assert.AreEqual(1, clearingPools.Count); Assert.AreEqual(0, idleList.Count); for (int i = 0; i < 5; i++) { connections[i].Close(); } Assert.AreEqual(0, clearingPools.Count); }