我有问题。我写了这个方法来打开sql连接。但它没有用。 为什么不这样做。
public SqlConnection connection( )
{
string DBName = ConfigurationManager.AppSettings["DBName"].ToString();
string ServerName = ConfigurationManager.AppSettings["ServerName"].ToString();
string UserId = ConfigurationManager.AppSettings["UserId"].ToString();
string DBPassword = ConfigurationManager.AppSettings["DBPassword"].ToString();
EMVTool.OSSPwdProcessor PwdPass = new EMVTool.OSSPwdProcessor();
String sClearPwd = "";
if (DBPassword.Length > 40)
sClearPwd = PwdPass.DecryptPwd(DBPassword);
else
sClearPwd = DBPassword;
string ConnectionString = "Server=" + ServerName + ";Database =" + DBName + ";UID =" + UserId + ";PWD =" + sClearPwd + ";MultipleActiveResultSets=True;";
SqlConnection connect = new SqlConnection(ConnectionString);
return connect;
}
我正在调用类似的方法来打开sql连接。
connection().Open();
答案 0 :(得分:3)
它没有用,因为你打开了一些东西但后来又使用了不同的实例。
要使其工作,请将函数返回值分配给局部变量:
using (SqlConnection conn = connection())
{
conn.Open();
//rest of code...
}