我已經創建了數據庫連接類來打開,關閉並創建連接字符串。我把它命名爲db_connections
。我創建了另一個名爲db_operations
的類來執行所有CRUD數據庫事務。我只想聲明一次連接字符串(爲此,假設我有一個表單輸入任何數據庫連接屬性,例如:server_name,db_name等)。需要建議:使用C#連接到mysql的數據庫連接類
我所知道的所有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
更安全嗎?
「不安全」是什麼意思? – RBarryYoung
哈哈,我不知道朋友,但有點從來沒有感到安全每次我寫代碼,我需要探索更多的每個代碼我寫,只是爲了確保我做了一個很好的代碼:D – r3d
-1:你是一個問我們這是否安全。你需要澄清你的意思。 – RBarryYoung