我正在创建一个帐户系统,在这里我使用SELECT * FROM查询来读取数据库中的所有数据,以查看输入的用户名是否已经存在但是这只返回最后一个用户数据库,因此如果输入的用户与排除上次保存的帐户的任何其他用户匹配,则不会识别用户已经存在,因此创建具有相同用户名的帐户。下面是我的子例程代码。任何人都可以帮我找到我做错了什么
Dim conn As New OleDbConnection Dim myqry As String = Nothing Dim mycmd As New OleDbCommand Dim mydr As OleDbDataReader
Private Sub btn_createAccount_Click(sender As System.Object, e As System.EventArgs) Handles btn_createAccount.Click
'Connecting to the database
Try
With conn
If .State = ConnectionState.Open Then .Close()
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database.accdb"
.Open()
End With
Catch ex As Exception
MessageBox.Show("Unable to connect", "error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Dim student_Name As String
Dim student_Username As String
Dim student_Password As String
Dim student_Group As String
student_Name = txt_firstname.Text & " " & txt_surname.Text
student_Username = LCase(txt_Username.Text)
student_Password = txt_password.Text
student_Group = cbo_tutorGroup.SelectedItem
'This chunk of code is reading the username column in the student account table in my database and doing a read to see if the inputted username is already existent in the table.
myqry = "SELECT * FROM TblStudents"
mycmd = New OleDbCommand(myqry, conn)
mydr = mycmd.ExecuteReader
While mydr.Read
Dim user As String = mydr("studentUser").ToString
If user = student_Username Then
MsgBox("Username already exists, please choose another")
Else
'If the username is not taken, the account credentials will be stored for use when logging in
Dim sqlQry As String
sqlQry = "INSERT INTO TblStudents(studentName, tutorGroup, studentUser, studentPass) VALUES('" & student_Name & "','" & student_Group & "','" & student_Username & "','" & student_Password & "')"
Dim cmd As New OleDbCommand(sqlQry, conn)
cmd.ExecuteNonQuery()
MsgBox("Your account has successfully been created")
Login_Student.Show()
Me.Close()
Exit Sub
End If
End While
答案 0 :(得分:0)
我认为你误解了你的结果。查询可能会返回许多行,但如果第一个与您的条件(user = student_Username)不匹配,则插入记录并退出该过程。
为什么不检查您的特定用户是否存在:
SELECT * FROM TblStudents WHERE studentUser = :student_Username
而不是检查每个学生?