我创建数据库连接类只是为了打开、关闭和创建连接字符串。我命名它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();
}
我想知道:
这是真的,使用静态变量不安全吗?如果是的话,有什么建议可以重构我的代码吗?
我关心在类
mysqlConn.Dispose()
中的每个函数中使用db_operations
,我只是调用db_operations
类来打开和关闭连接(而不是创建或修改connection string
)。那么仅用于mysqlConn.Close();
关闭连接就足够了吗?有什么建议可以让我
db_connections
更安全吗?