私はログインフォームを持っています。入力したパラメータがデータベース内のパラメータと一致するかどうかを確認して、ページにリダイレクトします。私は接続が開いているか閉じているときに例外をキャッチするためにコード内に条件を入れます。私はこのような解決策を探してみた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'ステートメントを使用して、すべてのメソッドでそれを作成してintiliazeします。おそらく関連しています:[ExecuteReaderはオープンで利用可能な接続が必要です。接続の現在の状態は[接続中]です(https://stackoverflow.com/questions/9705637/executereader-requires-an-open-and-available-connection-the-connections-curren) –
おそらくタイムリーな問題が発生しています接続が閉じている可能性がありますので、閉じていません。 – BugFinder
だから私は使用する必要があります使用して、使用内で接続を宣言しますか?そして私はまだ私の質問を条件付けするか、それとも不要になるでしょうか? –