我有一个登录表单。我的查询在我的数据库中运行并交叉检查输入的参数是否与数据库中的参数匹配,然后将您重定向到页面。我在代码中添加了一个条件来在连接打开或关闭时捕获异常。我试图寻找像这样的解决方案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
因此,我应该使用一个使用和声明连接内使用?我是否应该继续调整我的查询,否则它将变得不必要? –