如何使用SQL更新更新访问中的特定行?在我当前的代码中,我一直得到错误数据类型不匹配

时间:2016-04-07 11:46:33

标签: vb.net

在我当前的代码中,在添加SQL where语句以选择特定id

之前,我一直在使错误数据类型不匹配。
 Private Sub UpdateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UpdateButton.Click
    'tells your program the data source
    provider = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" 'refrences to the provider
    datafile = "C:\Users\Abdulaleem\Documents\Books.accdb" 'refers to the location of the file
    connectstring = provider & datafile ' combines the 2 variables
    myconnect.ConnectionString = connectstring ' this class allows you to connect to the database
    myconnect.Open() ' opens the databse
    Dim sqlupdate As String
    sqlupdate = "Update BooksTbl  set BookName='" & TitleTEXT.Text & "' , [BookAuthor]='" & AuthorTEXT.Text & "',[Genre] ='" & GenreTEXT.Text & "',[IsAvailable] = " & status & ",[DatePublished] = '" & DateTimeCHANGER.Text & "' , [PictureLocation] = '" & PiclocTEXT.Text & "' WHERE [ID] = '" & idshower.Text & "'"
    Dim cmd As OleDbCommand = New OleDbCommand(sqlupdate, myconnect) 'creating new database object 
    Try
        cmd.ExecuteNonQuery() ' executes our sql query
        cmd.Dispose() 'deleting from ram to stop interferences
        myconnect.Close() 'closes database and connection
        TitleTEXT.Clear()
        AuthorTEXT.Clear()
        GenreTEXT.Clear()
    Catch ex As Exception ' if the programs crashes then it will be caught here and put into the ex variable
        MsgBox(ex.Message) ' shows what error occured
        myconnect.Close()
    End Try
    myconnect.Close()

1 个答案:

答案 0 :(得分:0)

假设您的[ID]列是整数,请尝试从以下位置进行更改:

... WHERE [ID] ='“& idshower.Text&”'“

... WHERE [ID] =“& idshower.Text

在访问中,尝试将数字与字符串进行比较会导致消息“数据类型在条件表达式中不匹配”。

注意:除非您确定idshower.text实际上包含一个数字,否则最好在执行查询之前检查一下,否则访问会认为您正在尝试使用参数。

另外:您可能希望查看参数化查询,尽管它们通常会产生更多代码行,但可以保护您免受SQL注入攻击等攻击,并可以为您执行一些基本的类型转换。