Write a MySQL connection class

from the Artful MySQL Tips List

It is more efficient to use one persistent database connection than to repeatedly open and close connections, and the best way to do this is to write a connection class which Form1 can instantiate, open, and use until it is done. Should this class be contained within the application class Form1, or should within the application namespace but outside Form1? In case the application needs a second connection, outside Form1 is likely the simpler alternative. In Form1 code view, add this code just above the last right curly brace in the file:
  public class Connector {
    private MySqlConnection oConn;
    private string sConn;
    private Form parent;
    public Connector( Form _parent, string _sconn ) {
      this.parent = ( Form ) _parent;
      this.Init( _sconn );
    public Connector( Form _parent ) {
      parent = ( Form ) _parent;
    public void Init( string _sconn ) {
      this.sConn = _sconn;
      this.oConn = new MySqlConnection( sConn );
    public MySqlConnection Connection {
      get { return oConn; }
    public string ConnectionString {
      get { return sConn; }
    public void Open() {
      try {
      catch ( Exception ex ) {
        MessageBox.Show( ex.Message + Environment.NewLine + ex.StackTrace.ToString() );

Last updated 22 May 2009

Return to the Artful MySQL Tips page