sqlLink.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\Users\will\Documents\Computing\ComputingProjectDatabase.accdb';"
sqlLink.Open()
Try
If txtUsername.Text = "" Then
MsgBox("You did not enter a Username!")
Return
ElseIf txtPassword.Text = "" Then
MsgBox("You did not enter a Password!")
Return
ElseIf txtPassword.Text <> txtPasswordConf.Text Then
MsgBox("Your passwords do not match!")
Return
Else
Using sqlOrder As New OleDbCommand
Dim sqlCheck As New OleDbCommand
sqlCheck.CommandText = "SELECT count(*) FROM LoginSystem WHERE username = @username"
sqlCheck.Parameters.AddWithValue("@username", txtUsername.Text)
Dim oleRdr As OleDbDataReader
oleRdr = sqlCheck.ExecuteReader()
If oleRdr.HasRows = True Then
oleRdr.Read()
If oleRdr.Item(0) = 0 Then
sqlOrder.CommandText = "INSERT INTO LoginSystem ([Username], [Password], [PasswordConf]) VALUES ('" & txtUsername.Text & "','" & txtPassword.Text & "','" & txtPasswordConf.Text & "')"
sqlOrder.ExecuteNonQuery()
MsgBox("You have successfully registered, you can log in now!")
Else
MsgBox("Username is not currently available, please choose new username.")
End If
End If
End Using
End If
Catch ex As Exception
MsgBox("An error occurred:" & ex.Message)
End Try
sqlLink.Close()
Me.Close()
LoginScreen.Show()
End Sub
嘿,再次&gt;。&lt;这里只是一个小问题。每次我创建一组登录数据的副本(在这种情况下,用户名是Heather,密码是Trentshop)我返回的是一个尴尬的&#34;数据已被保存&#34;然后是一个很长的错误,说明数据没有保存,因为已经存在重复数据。
理想情况下,我希望它只是说&#34;用户名已经在使用中,请选择一个新的&#34;。我已经摆弄了ExceptDuplicateName和其他类似的类型。但由于某种原因,我无法理解这一点。我想我错过了一些非常明显的东西,在这种情况下,如果有人能帮我解决这个问题,那将是一个很大的帮助&gt;。&lt;
答案 0 :(得分:0)
处理此问题的最佳方法是在尝试插入用户名可用之前检查。您还应该使用参数化查询作为针对sql注入的工具。
Dim sqlCheck As New OleDbCommand
sqlCheck.CommandText = "SELECT count(*) FROM LoginSystem WHERE username = @username"
sqlCheck.Connection = sqlLink
sqlCheck.Parameters.AddWithValue("@username",txtUsername.Text)
Dim oleRdr as new OleDbReader = sqlCheck.ExecuteReader()
If oleRdr.HasRows = True Then
oleRdr.Read()
If oleRdr.Item(0) = 0 Then
'username is available and you can do insert command now
Else
'username is not available
End If
End If
您还应该使用&#39;使用&#39;在适当的情况下正确处理您的对象的声明,但由于这与您的问题相切,我只提供一个链接http://msdn.microsoft.com/en-us/library/htd05whh.aspx
或者您可以创建一个存储过程来处理整个过程,该过程返回一个值来表示成功或失败