Deleting from sqlite database using IN

眉间皱痕 提交于 2019-12-11 03:59:11

问题


I am deleting from an sqlite database using the ids of the records like this (the dirID is an array of the IDs):

Dim i As Integer = 0
        Dim conn As New SQLiteConnection("Data Source=" & DBPath)

        Dim cmd As New SQLiteCommand("DELETE FROM directory WHERE id IN (@ID)", conn)
        cmd.Parameters.AddWithValue("@ID", Join(dirID, ","))
        'conn.SetPassword(dbPassword)
        conn.Open()
        Try

            mytransaction = conn.BeginTransaction()
            '// delete directory //
            If dirID IsNot Nothing Then
                cmd.ExecuteNonQuery()
            End If

            mytransaction.Commit()
            conn.Close()

        Catch ex As Exception
            mytransaction.Rollback()
            strLastError = ex.Message
            Debug.Print(strLastError)
        Finally
            cmd.Dispose()
            conn.Dispose()
        End Try

The problem is that it doesn't always delete from the database, and its not throwing any errors.

Could there be a better way of deleting?


回答1:


That's not how parameters work.

If your IN list is 1, 2, 3, the command is trying to delete the record where ID equals "1, 2, 3", which is none. So no error is thrown and no record is deleted, because none was found. Thus, you will also find out that your code only works when your list contains 1 item.

Solution: You have to build your delete query (string manipulation), instead of working with parameters. Just beware of SQL Injection.

Update

From your code, it would be something like that:

Dim delcmd = "DELETE FROM directory WHERE id IN (" + Join(dirID, ",") + ")"
Dim cmd As New SQLiteCommand(delcmd, conn)

And no parameter call. Beware: I just tweaked your code, but it is not SQL Injection safe. You should read about that and about what's been written on the subject here in StackOverflow.



来源:https://stackoverflow.com/questions/6442205/deleting-from-sqlite-database-using-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!