【发布时间】:2018-10-21 04:33:14
【问题描述】:
我有这个代码,它的工作(有点)。
Dim connString As String = ConfigurationManager.ConnectionStrings("connectionstring").ConnectionString
Dim conn As New SqlConnection(connString)
conn.Open()
Dim comm As New SqlCommand("SELECT username, Password,type FROM users WHERE username='" & TextBox1.Text & "' AND Password='" & TextBox2.Text & "'", conn)
Dim reader As SqlDataReader
reader = comm.ExecuteReader
Dim count As Integer
count = 0
While reader.Read
count = count + 1
End While
If count = 1 Then
MessageBox.Show("username and password are correct")
Form2.Show()
Form2.Label1.Text = Me.TextBox1.Text
Form2.Label2.Text = reader(2).ToString
ElseIf count > 1 Then
MessageBox.Show("username and password are duplicated")
Else
MessageBox.Show("username and password are wrong")
End If
这行出错了:
Form2.Label2.Text = reader(2).ToString
and error is "Invalid attempt to read when no data is present"
为什么它说“没有数据”
我有数据库中的所有数据?
有人可以帮我更正这段代码吗? 谢谢你..
【问题讨论】:
-
您的 While 循环将继续,直到 reader.Read 返回 False 表示没有更多数据。您已到达数据末尾,无法访问 reader(2)。如果要获取类型,请在第一个 reader.Read 之后立即执行。
-
您不应在 SQL 查询中连接字符串。使用参数来防止 SQL 注入。此外,您永远不应该将密码存储为纯文本。
标签: vb.net sqldatareader