这个问题出现在更新语句的语法错误上,然后我不知道如何解决这个问题
Private Sub editStaff()
Try
If con.State = ConnectionState.Closed Then
con.Open()
End If
If IDTextBox.Text <> "" And FirstTextBox.Text <> "" And SecondTextBox.Text <> "" And UsernameTextBox.Text <> "" And PasswordTextBox.Text <> "" Then
strSQL = "update Staff set First_Name = '" & FirstTextBox.Text & "', " &
"Second_Name = '" & SecondTextBox.Text & "', " & "Username = '" & UsernameTextBox.Text & "', " &
"Password = '" & PasswordTextBox.Text & "'" & " where ID = " & CInt(IDTextBox.Text) & ""
Dim cmd As OleDbCommand = New OleDbCommand(strSQL, con)
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
con.Close()
MessageBox.Show("Update Successful")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
答案 0 :(得分:3)
由于某些原因,您的验证是否不包括ID文本框。我为此文本框添加了验证。 OrElse
是短路。一旦找到True,它就会停止检查条件并继续进行下一行。
此代码
If con.State = ConnectionState.Closed Then
con.Open()
End If
如果将数据库对象放在本地,则完全不需要。将它们保持在本地状态可确保您将它们封闭并用Using...End Using
块进行处置。
在您需要.Execute...
行之前的连接之前,请勿打开连接。使用参数来避免Sql注入。而且,没有所有单引号,双引号和“&”号,您的Update语句也更容易编写。
警告:在Access中,参数在Sql语句中出现的顺序必须与它们添加到.Parameters集合中的顺序匹配。
最后,您应该从不将密码存储为纯文本格式。我将留给您研究盐析和哈希并更正代码。
Private Sub editStaff()
Dim i As Integer
If Integer.TryParse(IDTextBox.Text, i) Then
MessageBox.Show("ID text box must be a number")
Return
End If
If IDTextBox.Text = "" OrElse FirstTextBox.Text = "" OrElse SecondTextBox.Text = "" OrElse UsernameTextBox.Text = "" OrElse PasswordTextBox.Text = "" Then
MessageBox.Show("Please fill in all text boxes")
Return
End If
Try
Using con As New OleDbConnection("Your connection string")
Dim strSQL = "Update Staff set First_Name = @FirstName, Second_Name = @SecondName, [Username] = @UserName, [Password] = @Password Where [ID] = @ID"
Using cmd As New OleDbCommand(strSQL, con)
With cmd.Parameters
.Add("@FirstName", OleDbType.VarChar).Value = FirstTextBox.Text
.Add("@SecondName", OleDbType.VarChar).Value = SecondTextBox.Text
.Add("@UserName", OleDbType.VarChar).Value = UsernameBox.Text
.Add("@Password", OleDbType.VarChar).Value = PasswordTextBox.Text
.Add("@ID", OleDbType.Integer).Value = CInt(IDTextBox.Text)
End With
con.Open()
cmd.ExecuteNonQuery()
End Using
End Using
MessageBox.Show("Update Successful")
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub