需要建议:使用C#连接mysql的数据库连接类

时间:2013-01-10 14:10:38

标签: c# mysql connection-string dispose static-variables

我创建了数据库连接类,只是为了打开,关闭和建立连接字符串。我把它命名为db_connections。我创建了另一个名为db_operations的类来执行所有CRUD数据库事务。

我的想法是: 我只想声明连接字符串一次(为此,假设我有一个表单来输入任何数据库连接属性,例如:server_name,db_name等)。

我所知道的所有C#都有全局变量cmiiw,我的搜索很多建议使用静态变量来存储数据。但有些人告诉我,使用静态变量并不安全。

所有代码都使用C#4.0。

以下是我的连接类的代码:

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);

        }

    }
}

从数据库连接表单中,我实例化了这样的类:

    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();
    }

我想知道:

  1. 是真的,使用静态变量不安全吗?如果是的话,是否有重构我的代码的建议?

  2. 我关注使用mysqlConn.Dispose(),在db_operations类的每个函数中,我只是调用db_operations类来打开和关闭连接(不是为了创建或修改{{1} }})。那么仅仅使用connection string关闭连接就足够了吗?

  3. 是否有任何建议让我mysqlConn.Close();更安全?

2 个答案:

答案 0 :(得分:0)

使用应用程序配置文件存储此类信息。如果使用asp.net,您可以使用Web.Config文件来存储所有连接字符串。如果您使用的是Winforms,则可以使用App.config执行相同的操作。

您可以在此处详细了解ConnectionStrings部分:http://msdn.microsoft.com/en-us/library/ms254494.aspx

您只需使用ConfigurationManager类访问此信息,如下所示:

MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["DBConnString"].ConnectionString);

这也是学习如何为所有类型的数据库和驱动程序定义连接字符串的好资源:http://www.connectionstrings.com/Articles/Show/store-connection-string-in-web-config

答案 1 :(得分:0)

不,静力学通常不安全。但是你以一种他们不打算使用的方式使用它们。例如,您创建类db_connections的实例,然后将值分配给类db_connections的静态属性,之后您使用该类的对象方法,该方法又将再次使用静态属性。静态属性绝不会连接到它们声明的类的特定对象实例。静态属性有点像PHP中的全局变量 - 在给定的上下文中(通常整个应用程序,每个线程也是可能的),它只存在一次。因此,您可以将配置信息存储为类的静态属性,但您必须记住,您可以随时只保留一个信息。例如,您可以不为不同的数据库创建两个配置。因此,无论何时更改静态属性,都要为访问该属性的每段代码更改它。

关于静态属性的一个小例子:

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();
   }
}

输出就是:

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

对class1.WriteText1()的最后一次调用写入与class2.WriteText1相同的输出。对象class1和class2都访问相同的静态属性Text1。这与Text2等实例属性不同。两个对象都包含一个名为Text2的属性,但值不同,它们是单个对象的一部分。更改单个对象的该属性的值,它只在该对象中更改,其他对象虽然具有相同的属性,但保留其自己的值。