【发布时间】:2017-10-20 19:56:23
【问题描述】:
我有一个登录表单。我的查询在我的数据库中运行并交叉检查输入的参数是否与数据库中的参数匹配,然后将您重定向到一个页面。我在代码中设置了一个条件,以在连接打开或关闭时捕获异常。我曾尝试查找像 one 和其他这样的解决方案。
我做了以下事情。
- 包括使用
但它在运行时仍然显示此错误
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 Username=@user AND Password=@password;";
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 Username=@user AND Password=@password;";
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-statement 在每个方法中创建和启动它。可能相关:ExecuteReader requires an open and available Connection. The connection's current state is Connecting -
您可能遇到了时间问题,您的连接可能正在关闭......所以它没有关闭..
-
所以我应该使用 using 并在 using 中声明连接?我是否应该仍然对我的查询进行条件处理,否则它会变得没有必要?
-
这似乎是一个网络应用程序,您可能将连接存储在某个静态字段中。因此,当一个请求进来时,检查连接是否打开并尝试执行命令 - 另一个请求可能会关闭其间的连接。如上所述 - 永远不要这样做,每次都创建新连接(它不会真正创建到数据库的新连接,因为连接存储在池中)。
-
你有两个连接也很奇怪:1)
Connect.con2)connection.con。但是,两者都应该不是静态的!否则我上面的链接不相关,而是重复的。