我有一個登錄表單。我的查詢在我的數據庫中運行並交叉檢查輸入的參數是否與數據庫中的參數匹配,然後將您重定向到頁面。我在代碼中添加了一個條件來在連接打開或關閉時捕獲異常。我試圖尋找像這樣的解決方案one和其他人。ExecuteReader需要一個開放且可用的連接,但連接已打開且不起作用
我已經完成了以下工作。
- 包括usings
但是其仍顯示出在運行時出現此錯誤
ExecuteReader需要一個開放和可用的連接。連接的當前狀態已關閉。
這是我的代碼:
public void LWAPLogin(string username, string password)
{
string wrongCredentials = "Username does not exist. Or password is incorrect";
string query = "Select Username, Password from LWAP where [email protected] AND [email protected];";
using (SqlCommand command = new SqlCommand(query, Connect.con))
{
command.Parameters.Add("@user", SqlDbType.VarChar, 50).Value = username;
command.Parameters.Add("@password", SqlDbType.VarChar, 50).Value = password;
try
{
if (connection.con.State == ConnectionState.Open)
{
using (SqlDataReader dr = command.ExecuteReader())
{
if (dr.Read())
Response.Redirect("LWAPHome.aspx");
else
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + wrongCredentials + "');", true);
dr.Close();
}
connection.con.Close();
}
else if (connection.con.State == ConnectionState.Closed)
{
connection.con.Open();
using (SqlDataReader dr = command.ExecuteReader())
{
if (dr.Read())
Response.Redirect("LWAPHome.aspx");
else
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + wrongCredentials + "');", true);
dr.Close();
}
connection.con.Close();
}
}
finally
{
//connection.con.Open();
}
}
}
從老鄉程序員得到提醒後。我改變了我的代碼,問題得到解決。但是現在我有一個新問題。當一切正常時,它假設重定向到新頁面,但它不是。只是將頁面url更改爲所需的頁面,但仍保留在登錄頁面上。
下面是我的編輯代碼:
public void LWAPLogin(string username, string password)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["tlcString"].ConnectionString))
{
string wrongCredentials = "Username does not exist. Or password is incorrect";
string query = "Select Username, Password from LWAP where [email protected] AND [email protected];";
using (SqlCommand command = new SqlCommand(query, con))
{
command.Parameters.Add("@user", SqlDbType.VarChar, 50).Value = username;
command.Parameters.Add("@password", SqlDbType.VarChar, 50).Value = password;
con.Open();
using (SqlDataReader dr = command.ExecuteReader())
{
if (dr.Read())
Response.Redirect("LWAPHome.aspx");
else
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + wrongCredentials + "');", true);
dr.Close();
}
//connection.con.Close();
}
con.Close();
}
}
請參閱image它現在顯示的錯誤。我嘗試了使用不同的瀏覽器,但他們都做同樣的事情。
爲什麼重用'SqlConnection'呢?這導致了這樣的問題。相反,使用'using'語句在每種方法中創建並使用它。可能相關:[ExecuteReader需要一個開放和可用的連接。連接的當前狀態是連接](https://stackoverflow.com/questions/9705637/executereader-requires-an-open-and-available-connection-the-connections-curren) –
你可能會遇到一個問題連接可能會關閉...所以它不關閉.. – BugFinder
因此,我應該使用一個使用和聲明連接內使用?我是否應該繼續調整我的查詢,否則它將變得不必要? –