-1

接続文字列を開いたり、閉じたり、作成したりするためだけに、データベース接続クラスを作成しました。と名付けましたdb_connectionsdb_operationsすべての CRUD データベース トランザクションを実行するという名前の別のクラスを作成しました 。

私の考えは、接続文字列を一度宣言したいだけです(このために、データベース接続属性を入力するためのフォームが1つあると仮定します。たとえば、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て接続を開いたり閉じたりするだけです(を作成または変更するのではありませんconnection string)。それでmysqlConn.Close();、接続を閉じるために使用するだけで十分ですか?

  3. 私をdb_connectionsより安全にするための提案はありますか?

4

2 に答える 2

0

いいえ、静的は一般的に安全ではありません。しかし、意図されていない方法でそれらを使用します。たとえば、クラス db_connections のインスタンスを作成し、クラス db_connections の静的プロパティに値を割り当てた後、そのクラスのオブジェクト メソッドを使用して、再び静的プロパティを使用します。静的プロパティは、それらが宣言されているクラスの特定のオブジェクト インスタンスに接続されることはありません。静的プロパティは、PHP のグローバル変数に少し似ています - 特定のコンテキスト (通常はアプリケーション全体、スレッドごとも可能) で、一度だけ存在します。したがって、構成情報をクラスの静的プロパティに保存できますが、一度に保持できる情報は 1 つだけであることに注意する必要があります。たとえば、異なるデータベースに対して 2 つの構成を作成することはできません。

静的プロパティの小さな例:

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 というプロパティが含まれていますが、値は異なり、個々のオブジェクトの一部です。単一のオブジェクトのそのプロパティの値を変更すると、そのオブジェクト内でのみ変更され、他のオブジェクトは同じプロパティを持っていますが、独自の値を保持します。

于 2013-01-10T14:31:29.913 に答える
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

于 2013-01-10T14:20:31.270 に答える