接続文字列を開いたり、閉じたり、作成したりするためだけに、データベース接続クラスを作成しました。と名付けましたdb_connections
。db_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();
}
私は知りたいです:
安全ではない静的変数を使用すると、それは本当ですか? はいの場合、コードをリファクタリングするための提案はありますか?
クラス
mysqlConn.Dispose()
内のすべての関数内で、db_operations
クラスを呼び出しdb_operations
て接続を開いたり閉じたりするだけです(を作成または変更するのではありませんconnection string
)。それでmysqlConn.Close();
、接続を閉じるために使用するだけで十分ですか?私を
db_connections
より安全にするための提案はありますか?