我有一个用于获取SqlDataReader
的代码,我使用customer_id
从SQL Server中读取SqlDataReader
。我使用断点和逐步调试测试女巫,我理解connection.close
条件不是编译,编译器直接跳转到 string strQuery = "select customer_id from Registration where username=@username and password=@password";
SqlConnection connection1 = DBConnection.getConnection();
connection1.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection1;
cmd.CommandText = strQuery;
cmd.Parameters.AddWithValue("username", txt1_username.Text);
cmd.Parameters.AddWithValue("password", txt2_password.Text);
string customer_id = cmd.ExecuteScalar() as string;
connection1.Close();
if (customer_id == null)
{
Messages myMsg = new Messages();
myMsg.CreateMessageAlert("The User does not Registered or your using incorect username or password");
}
else {
Session["customer_id"] = customer_id;
}
行:
{{1}}
答案 0 :(得分:0)
<强>更新强>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text
<img src=http://cdn-img.health.com/sites/default/files/styles/400x400/public/styles/400x400/public/styles/main/public/how-take-care-cat-400x400.jpg?itok=ta2kPB58>
</p>
这是您的问题的完整解决方案。 不需要每次都打开连接。确保连接在使用后关闭。
答案 1 :(得分:0)
虽然问题不是很清楚,但您可以尝试修改以下代码:
select count(*)
,select customer_id
)。为什么在第一种情况下,您在另一个案例中执行ExecuteScalar()
和ExecuteReader()
? SqlCommand()
等。阅读Retrieving Multiple Result Sets using NextResult <强>更新强>
更新的代码看起来更清晰明了,但您没有明白我的最后评论。如果您select count(customer_id)
,您将得到一项您不需要的计数。为什么不简单地select customer_id
并检查它是否被退回?
示例:
//string strQuery = "select count(customer_id) from Registration where username=@username and password=@password";
string strQuery = "select customer_id from Registration where username=@username and password=@password";
SqlConnection connection1 = DBConnection.getConnection();
connection1.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection1;
cmd.CommandText = strQuery;
cmd.Parameters.AddWithValue("username", txt1_username.Text);
cmd.Parameters.AddWithValue("password", txt2_password.Text);
//int intRowCount = (int)cmd.ExecuteScalar();
string customer_id = cmd.ExecuteScalar() as string;
//txt1_username.Text = intRowCount.ToString(); <-- What's this?
connection1.Close();
//if (intRowCount == 1)
if (customer_id == null)
{
// user does not exist, because sql returned no rows
... <-- do something here
} else {
Session["customer_id"] = customer_id;
}
更新#2:
进行问题排查
确保txt1_username.Text
和txt2_password.Text
具有预期值。可能是您在某处重置Text
,这可能是查询未返回结果的原因。尝试对代码中的值进行硬编码,例如
cmd2.Parameters.AddWithValue("username", "admin");
cmd2.Parameters.AddWithValue("password", "123");
在Sql Server Management Studio(或其他工具)中复制粘贴整个sql并从此处运行它以确保返回的结果。
答案 2 :(得分:0)
这是因为您的用户名不再是用户名。它实际上是1,因为行
int intRowCount = (int) cmd.ExecuteScalar();
txt1_username.Text = intRowCount.ToString(); <-- RED FLAG
所以在If里面,你实际上正在运行
SELECT customer_id FROM registration WHERE username=1 and password=my_password
评论第15行,你应该做得很好。