1

我有个问题。我写了这个方法来打开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();
4

1 回答 1

4

它不起作用,因为您打开了某些东西,但之后又使用了不同的实例。

要使其工作,请将函数返回值分配给局部变量:

using (SqlConnection  conn = connection())
{
    conn.Open();
    //rest of code...
}
于 2012-09-20T08:37:34.430 回答