gpt4 book ai didi

c# - ASP.NET 中不存在数据时的无效读取尝试

转载 作者:行者123 更新时间:2023-11-30 19:10:06 25 4
gpt4 key购买 nike

我正在使用C#学习ASP.NET,我尝试将身份验证代码编写为

SqlCommand command = new SqlCommand("Select [ID] from [Inspector] WHERE [ID] ='111' AND [Password] ='111';", conn);

SqlDataReader dr = command.ExecuteReader();

if (dr[0].ToString() == username)
{
Session["UserAuthentication"] = username;
Session.Timeout = 1;
Response.Redirect("About.aspx");
}
else{
// ...
}

ID 在 SQL Server 中是 numeric 类型。

问题是我总是遇到异常:

Invalid attempt to read when no data is present.

在这部分:if (dr[0].ToString() == username)

我尝试直接执行确切的SQL语句,我可以得到结果。

最佳答案

您需要遍历读取器返回的行 - 使用如下代码:

SqlDataReader dr = command.ExecuteReader();

if(dr.Read())
{
if (dr[0].ToString() == username)
{
Session["UserAuthentication"] = username;
Session.Timeout = 1;
Response.Redirect("About.aspx");
}
else {
// ...
}
}

您需要至少调用 SqlDataReader 上的 .Read() 一次才能真正读取数据。

如果你打算读取尽可能多的行,你应该使用

while (dr.Read())
{
.....
}

并处理返回的多行。

关于c# - ASP.NET 中不存在数据时的无效读取尝试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19864837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com