更新访问错误

时间:2009-05-12 10:08:04

标签: vb.net ms-access updating

    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()

下面的更新命令一直给我这个错误:“从字符串转换”'WHERE [Username] ='“到'Double'类型无效。”而且我不知道为什么。 aUserName字段是一个String字段,我检查以确保它已填充。

            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

2 个答案:

答案 0 :(得分:5)

你有一个错字。您在sql字符串末尾使用 + concat字符而不是& 字符

<强>错误

cmd.CommandText = "UPDATE Users SET [First Name] = '" & aName & _ 
                  "', [Last Name] = '" & aSurname & _
                  "', [Contact Number] = '" & aContactNum & _
                  "', [Password] = '" & aPassword & "', [User Rights] = '" & _
                  aUserRights + "' WHERE [Username] = '" + aUserName + "' "
'                             ^                          ^           ^

从右

cmd.CommandText = "UPDATE Users SET [First Name] = '" & aName & _
                  "', [Last Name] = '" & aSurname & _
                  "', [Contact Number] = '" & aContactNum & _
                  "', [Password] = '" & aPassword & "', [User Rights] = '" & _
                  aUserRights & "' WHERE [Username] = '" & aUserName & "' "
'                             ^                          ^           ^

答案 1 :(得分:0)

您的SQL代码使用[Username]

cmd.CommandText = "UPDATE Users SET ... [Username]...

您注释了使用[User Name]的代码:

'rsAddRecs = rsConn.Execute("UPDATE Users ... [User Name]...

错误的列名是否可能是问题的根源?

另一个想法是:您是否清理了参数值,例如:该值可能包含一个扰乱动态SQL的单引号。在任何情况下,我认为您应该考虑使用预准备语句(甚至是PROCEDURES)并使用Parameter对象来调用SQL,从而将参数值的清理推迟到OLE DB提供程序,这当然会比主题知道更多。你或我:)。