Updating access error
Question
Dim conn As OleDbConnection
Dim cmd As OleDbCommand
Public Sub openDB()
conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Application.StartupPath & "\VFMS_DB.mdb;" & "Jet OLEDB:System Database=Security.mdw;User ID=Adster;Password=300624;")
conn.Open()
End Sub
Public Function UpdateUser() As Integer
Dim retCode As New Integer
Try
openDB()
cmd = conn.CreateCommand()
The update command below keeps giving me this error: "Conversion from string "' WHERE [Username] = '" to type 'Double' is not valid." and I don't know why. The aUserName field is a String field and I checked to make sure it's populated.
cmd.CommandText = "UPDATE Users SET [First Name] = '" & aName & "', [Last Name] = '" & aSurname & "', [Contact Number] = '" & aContactNum & "', [Password] = '" & aPassword & "', [User Rights] = '" & aUserRights + "' WHERE [Username] = '" + aUserName + "' "
cmd.ExecuteNonQuery()
conn.Close()
'rsAddRecs = rsConn.Execute("UPDATE Users ([First Name], [Last Name], [Contact Number], [User Name], [Password], [User Rights]) VALUES ('" & aName & "','" & aSurname & "','" & aContactNum & "','" & aUserName & "','" & aPassword & "','" & aUserRights & "')")
retCode = 0
'rsConn.Close()
Return retCode
Catch ex As Exception
MessageBox.Show(ex.ToString, ex.Message, MessageBoxButtons.OK)
retCode = 1
Return retCode
End Try
End Function
Solution
You have a typo. You're using + concat characters at the end of the sql string instead of & characters
Wrong
cmd.CommandText = "UPDATE Users SET [First Name] = '" & aName & _
"', [Last Name] = '" & aSurname & _
"', [Contact Number] = '" & aContactNum & _
"', [Password] = '" & aPassword & "', [User Rights] = '" & _
aUserRights + "' WHERE [Username] = '" + aUserName + "' "
' ^ ^ ^
Right
cmd.CommandText = "UPDATE Users SET [First Name] = '" & aName & _
"', [Last Name] = '" & aSurname & _
"', [Contact Number] = '" & aContactNum & _
"', [Password] = '" & aPassword & "', [User Rights] = '" & _
aUserRights & "' WHERE [Username] = '" & aUserName & "' "
' ^ ^ ^
OTHER TIPS
You SQL code uses [Username]
:
cmd.CommandText = "UPDATE Users SET ... [Username]...
Whereas you commented out code used [User Name]
:
'rsAddRecs = rsConn.Execute("UPDATE Users ... [User Name]...
Could the wrong column name be the source of the problem?
Another thought: have you sanitized your parameter values e.g. could the value contain a single quote that is upsetting the dynamic SQL. In any case, I think you should consider using prepared statements (or even PROCEDURES) and using Parameter objects to call the SQL, thereby deferring the sanitizing of the parameter values to the OLE DB provider, which will of course know more about the subject than you or I :)