ADD SQL QUERY STAT

后端 未结 1 1929
被撕碎了的回忆
被撕碎了的回忆 2021-01-28 19:08

I\'m trying to update the records from textboxes into the Access database, I\'m wondering every time I hit save, it generates an error

An unhandled excep

1条回答
  •  终归单人心
    2021-01-28 19:50

    You are trying to set an UPDATE command text for the SelectCommand of the Adapter. This, of course has no way to be successful. Last but not least the UPDATE command text doesn't contain a WHERE clause, and so, if executed, it updates every record in the table tbl_empinfo with the same data.

    In this context there is no need to use an adapter. You could simply execute the command, providing an appropriate WHERE clause and the values for the other parameters

       Dim sqlQuery As String = "UPDATE tbl_empinfo " & _
            "SET FirstName=?, LastName=?, Department=?, " & _
            "Status=?, Years=? " & _
            "WHERE empID=?"
    
        Dim cmd As New OleDbCommand
        With cmd
            .CommandText = sqlQuery
            .Connection = con
            .Parameters.AddWithValue("@p1", empFName)
            .Parameters.AddWithValue("@p2", empLName)
            .Parameters.AddWithValue("@p3", empDept)
            .Parameters.AddWithValue("@p4", empStat)
            .Parameters.AddWithValue("@p5", empYears)
            .Parameters.AddWithValue("@p6", empNum)
            .ExecuteNonQuery()
        End With
    

    After this you could call the code that reloads the data to fill your grid

        sqlQuery = "SELECT * FROM tbl_empinfo"
        Dim cmd1 As New OleDbCommand
        Dim da As New OleDbDataAdapter
        Dim Table As New DataTable
    
        With cmd1
            .CommandText = sqlQuery
            .Connection = con
            With da
                .SelectCommand = cmd1
                .Fill(Table)
            End With
            With DataGridView1
                .DataSource = Table
            End With
        End With
    

    Notice that I have changed the name of the command and the adapter to a less confusing names. SqlCommand And SqlDataAdapter are the names of the classes equivalent to the OleDbCommand and OleDbDataAdapter but used for Sql Server. At first sight I was thinking that you were trying to use the SqlClient classes to update an MS-Access database.

    0 讨论(0)
提交回复
热议问题