这不是建立数据库的方法;您不会为了获取特定结果而定义无限数量的表,所有表都包含相似的信息。相反,您应该将所有播放列表数据放入一个表中,但提供足够的字段来区分查询返回的值。一个例子(简化,它不是一个完整的解决方案!):
import sqlite3
def create_database():
with sqlite3.connect('all_playlists.db') as conn:
c = conn.cursor()
c.execute("DROP TABLE playlists") # Gets messy if you re-run the code otherwise
c.execute("""
CREATE TABLE IF NOT EXISTS playlists(
playlist_name TEXT,
username TEXT,
song_title TEXT)
""")
def add_playlist(playlist_name, username, songs):
with sqlite3.connect('all_playlists.db') as conn:
c = conn.cursor()
for song in songs:
c.execute("""
INSERT INTO playlists VALUES (?, ?, ?)
""", (playlist_name, username, song))
def get_all_playlists(username):
with sqlite3.connect('all_playlists.db') as conn:
c = conn.cursor()
c.execute("""
SELECT DISTINCT playlist_name
FROM playlists
WHERE username = ?
""", (username,))
return c.fetchall()
def get_songs_in_playlist(playlist, username):
with sqlite3.connect('all_playlists.db') as conn:
c = conn.cursor()
c.execute("""
SELECT song_title
FROM playlists
WHERE playlist_name = ?
AND username = ?
""", (playlist, username))
return c.fetchall()
if __name__ == '__main__':
create_database()
# Add some users and songs
add_playlist('happy times', 'John Smith', ['Song A', 'Song B'])
add_playlist('sad times', 'John Smith', ['Song C', 'Song D'])
add_playlist('something else', 'John Smith', ['Song E', 'Song F',
'Song G'])
add_playlist('running out of ideas', 'Janet', ['Song F', 'Song G',
'Song H'])
# Get playlists of John Smith
print("John Smith's playlists are: ", get_all_playlists('John Smith'))
# Get Janet's
print("Janet's playlists are: ", get_all_playlists('Janet'))
# Get all songs in happy times
print("All songs in happy times playlist by John are: ",
get_songs_in_playlist('happy times', 'John Smith'))
如果您的应用程序变得足够大,您也不应该仅依靠名称来识别用户,因为您会遇到名称冲突。在这种情况下,您需要一个将用户映射到用户 ID 的登录系统,然后您可以使用它来连接表。