简体   繁体   中英

deleting items from sql table in VB.net

I am trying to remove all of the records from an SQL table in VB.net. My code for doing this is:

    Dim SQL As String = "DELETE FROM MTable"
    Using CN As New OleDb.OleDbConnection(AddPage.DBConnect)
        CN.Open()
        Dim DBcmd As New OleDb.OleDbCommand(SQL, CN)
        DBcmd.ExecuteNonQuery()
        CN.Close()
    End Using

    'SQLDataset.Tables("Mtable").Clear()

    MtableTA.Update(SQLDataset)

    SQL = "DELETE FROM ITable"
    Using CN As New OleDb.OleDbConnection(AddPage.DBConnect)
        CN.Open()
        Dim DBcmd As New OleDb.OleDbCommand(SQL, CN)
        DBcmd.ExecuteNonQuery()
        CN.Close()
    End Using

    ' SQLDataset.Tables("ITable").Clear()

    ITableTA.Update(SQLDataset)

The Mtable and Itables are the SQL tables, while MtableTA and ItableTA are table adapters.

I also end up getting an error which states

    An unhandled exception of type 'System.Data.DBConcurrencyException' occurred in System.Data.dll
    Additional information: Concurrency violation: the UpdateCommand affected 0 of the expected 1 records.

The section where this occurss is not provided in the code above, but is a call to MtableTA.update(SQLDataset). Any help would be very much appreciated. I'm also using OLEDB if that helps.

You have directly deleted the rows bypassing the TableAdapter methods to do that. So it is highly probable that when you call the Update there are some conflicts with data changed on the TableAdapter and no more available in the database.
After removing the rows directly using OleDbCommand.ExecuteNonQuery you should simply refresh the TableAdapters to sync them with the real situation on your physical database table

SQLDataset.Tables("ITable").Clear()
ITableTA.Adapter.Fill(SQLDataSet.ITable)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM