我已经创建了数据库连接类来打开,关闭并创建连接字符串。我把它命名为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