Search code examples
c#mysqlconnection-stringdisposestatic-variables

Need Suggestion: database connection class to connect to mysql using C#


I've created database connection class just to open, close, and make a connection string. I named it db_connections . I created another class named db_operations to do all CRUD database transactions.

My idea is: I just want to declare the connection string once (for this, assume I've got one form to input any database connection attributes, eg: server_name, db_name, etc).

All that I know C# does have global variable cmiiw, and my searching many suggest to use a static variable to store data. But some told me that using static variable is not safe.

All the code is using C# 4.0.

Here is the code for my connections class:

class db_connections : databases_abstract
{

    private static string dbname;
    private static string dbuser;
    private static string dbpass;
    private static string dbserver;

    public MySqlConnection mysqlConn;

    public static string DB_NAME
    {
        get
        {
            return dbname;
        }
        set
        {
            dbname = value;
        }
    }

    public static string DB_USER
    {
        get
        {
            return dbuser;
        }
        set
        {
            dbuser = value;
        }
    }

    public static string DB_PASSWORD
    {
        get
        {
            return dbpass;
        }
        set
        {
            dbpass = value;
        }
    }

    public static string DB_SERVER
    {
        get
        {
            return dbserver;
        }
        set
        {
            dbserver = value;
        }
    }


    protected override string db_make_connstring(string dbserver, string dbuser, string dbpass, string dbname)
    {
        //## Our connection string
        string connString = String.Format("server={0};user id={1}; password={2}; database={3}; pooling=false",
        dbserver, dbuser, dbpass, dbname);

        return connString;
    }

    public override Boolean db_open_connection()
    {
        try
        {
            //## Initialise the connection
            mysqlConn = new MySqlConnection(
                this.db_make_connstring(db_connections.dbserver, db_connections.dbuser,
                    db_connections.dbpass, db_connections.dbname)
                );
            if (mysqlConn != null)
            {
                mysqlConn.Close();
            }
            //## Open the connection
            mysqlConn.Open();

            return true;
        }
        catch (Exception Ex)
        {
            System.Windows.Forms.MessageBox.Show(Ex.Message, "Error",
                System.Windows.Forms.MessageBoxButtons.OK,
                System.Windows.Forms.MessageBoxIcon.Error);
            return false;
        }
    }

    public override void db_close_connection()
    {
        try
        {
            if (mysqlConn != null)
            {
                mysqlConn.Close();
                mysqlConn.Dispose();
            }
        }
        catch(Exception Ex)
        {
            System.Windows.Forms.MessageBox.Show(Ex.Message, "Error",
                System.Windows.Forms.MessageBoxButtons.OK,
                System.Windows.Forms.MessageBoxIcon.Error);

        }

    }
}

From the database connection form I instantiated that class like this:

    db_connections db_conn = new db_connections();
    db_connections.DB_SERVER = txtDbServer.Text;
    db_connections.DB_NAME = txtDbName.Text;
    db_connections.DB_USER = txtDbUser.Text;
    db_connections.DB_PASSWORD = txtDbPass.Text;

    //##Just testing the connection
    //##Once the connection succes, the database setting cannot be opened again
    //##until the application is terminated or any really special event request
    if (db_conn.db_open_connection() == true)
    {
       MessageBox.Show("Successfully connect to the database!!");
       this.Owner.Controls["btnUpload"].Enabled = true;
       this.Owner.Controls["btnDb"].Enabled = false;
       this.Close();
    }

I want to know:

  1. Is that true, using static variable not safe? if yes, any suggestions to refactor my code?

  2. I concern using mysqlConn.Dispose(), inside every function in db_operations class, I just call db_operations class to open and close connection (not to create or modify the connection string). So is that enough just to use mysqlConn.Close(); to close the connection?

  3. Is there any suggestion to make my db_connections safer?


Solution

  • No, statics are not generally unsafe. But you use them in a way they are not meant to be used. For instance, you create an instance of class db_connections, then assign values to the static properties of class db_connections, after that you use an object method of that class that in turn uses the static properties again. Static properties are in no way connected to a specific object instance of the class they are declared in. A static property is a bit like a global variable in PHP - in a given context (usually the whole application, per thread is also possible), it only exists once. So you can store configuration information i static properties of a class, but you have to keep in mind that you can keep only one information at any time. You could for instance not create two configurations for different databases. So whenever you change a static property, you change it for every piece of code accessing that property.

    A small example on static properties:

    public class TestClass
    {
    
         public static string Text1 { get; set; }
         public string Text2 { get; set; }
    
         public void WriteText1()
         {
             Console.WriteLine(TestClass.Text1);
         }
    
         public void WriteText2()
         {
             Console.WriteLine(this.Text2);
         }
    }
    
    
    
    public class Program
    {
    
       public static void Main(string[] args)
       {
           TestClass class1 = new TestClass;
           TestClass.Text1 = "Some Text";
           class1.Text2 = "More Text";
    
           class1.WriteText1();
           class1.WriteText2();
    
           TestClass class2 = new TestClass;
           TestClass.Text1 = "Another Text";
           class2.Text2 = "And a fourth text";
    
           class2.WriteText1();
           class2.WriteText2();
    
           class1.WriteText1();
       }
    }
    

    the output on this is:

    Some Text
    More Text
    Another Text
    And a fourth text
    Another Text
    

    the last call on class1.WriteText1() writes the same output as class2.WriteText1. Both objects, class1 and class2, access the same static property, Text1. This is different to instance properties like Text2. Both objects contain a property called Text2, but the values are different, they are part of an individual object. Change the value of that property for a single object and it is only changed within that object, other objects, while they have the same property, retain their own value.