如何只显示查询中的某些单词

时间:2018-04-09 18:40:10

标签: python sql python-3.x sqlite

在我的测试程序中,用户可以保存播放列表,他们可以随意调用它们。例如,如果用户James Smith保存名为My Playlist的播放列表,则该表的名称将为James Smith_My Playlist。当他们想要搜索所有他们的播放列表时,我将如何制作呢?显示以James Smith_开头的播放列表但不显示他们的名字或在输出中强调。

我的预期结果:

  • 用户保存播放列表
  • 播放列表称为FirstName LastName_NameOfPlaylist
  • 用户选择"查看所有播放列表[表格]"
  • 输出显示以FirstName LastName_开头的表格但未在输出中显示NameOfPlaylist

我知道如何查询以某些字母/单词开头的表格,我只是无法弄清楚如何输出它,没有FirstName LastName_

1 个答案:

答案 0 :(得分:0)

这不是设置数据库的方法;为了获得具体结果,您不会定义无限数量的表,所有表都包含类似的信息。相反,您应该将所有播放列表数据放在一个表中,但提供足够的字段来区分查询返回的值。一个例子(简化,它不是一个完整的解决方案!):

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的登录系统,然后您可以使用它来连接表。