sql DELETE不工作,但SELECT呢?

时间:2016-03-30 16:16:40

标签: python sqlite

我正在尝试弄清楚当我使用DELETE时我的查询无效的原因,但是当我使用SELECT时它会起作用:

    def delete_artists_and_albums_without_tracks(self, test=True):
        # *it is better to use `NOT EXISTS` instead  `NOT IN` because it will
        #  also delete the rows containing null id's

        if test == True:
            # Check the albums
            self._cursor.execute('''
SELECT Ab.Title
FROM CoreAlbums Ab
WHERE NOT EXISTS (
    SELECT T.AlbumID
    FROM CoreTracks T
    WHERE T.AlbumId = Ab.AlbumId)''')
            albums=self._cursor.fetchall()

            # Check the artists
            self._cursor.execute('''
SELECT Ar.Name
FROM CoreArtists Ar
WHERE NOT EXISTS (
    SELECT T.ArtistID
    FROM CoreTracks T
    WHERE T.ArtistID = Ar.ArtistID)''')     
            artists=self._cursor.fetchall()

            return albums, artists


        # Delete the albums
        self._cursor.execute('''
DELETE 
FROM CoreAlbums Ab
WHERE NOT EXISTS (
    SELECT T.AlbumID
    FROM CoreTracks T
    WHERE T.AlbumId = Ab.AlbumId)''')
        self._connection.commit()

        # Delete the artists
        self._cursor.execute('''
DELETE 
FROM CoreArtists Ar
WHERE NOT EXISTS (
    SELECT T.ArtistID
    FROM CoreTracks T
    WHERE T.ArtistID = Ar.ArtistID)''') 

        self._connection.commit()

当我使用SELECTtest=True)运行时,我得到以下输出:

[('album_name1',), ('album_name2',)]
[('artist_name1',), ('artist_name2',)]

但是当我使用DELETEtest=False)时,我收到以下错误:

Traceback (most recent call last):
  File "Database.py", line 563, in <module>
    printl(db.delete_artists_and_albums_without_tracks(False))
  File "Database.py", line 396, in delete_artists_and_albums_without_tracks
    WHERE T.AlbumId = Ab.AlbumId)''')
sqlite3.OperationalError: near "Ab": syntax error

我想我正在跳过一些非常基本的东西,但我遇到了找错的问题..

重复答案的帖子对我没有帮助,我仍然遇到Ab问题。我通过这样做来解决这个问题:

self._cursor.execute('''SELECT AlbumID FROM CoreTracks GROUP BY AlbumID''')
album_ids=[item[0] for item in self._cursor.fetchall()]
query='''DELETE FROM CoreAlbums WHERE NOT AlbumId IN ({})'''.format(','.join('?'*len(album_ids)))
self._cursor.execute(query, album_ids)

0 个答案:

没有答案