Py学习  »  DATABASE

为什么我从Spotify的API中提取的数据不能存储在MySQL数据库中?

anon • 9 月前 • 117 次点击  

我已连接到Spotify的Python API,以提取搜索艺术家的前20首曲目。我正试图将MySQL工作台中的数据存储在一个名为“spotify_api”的数据库中,该数据库是我创建的,名为“spotify”。在我添加代码连接到MySQL Workbench之前,我的代码工作正常,能够提取曲目列表,但我在将代码连接到数据库时遇到了问题。以下是我为提取数据并将其存储到数据库中而编写的代码:


    import spotipy
    from spotipy.oauth2 import SpotifyClientCredentials

    import mysql.connector


    mydb = mysql.connector.connect(
        host = "localhost",
        user = "root",
        password = "(removed for question)",
        database = "spotify_api"
    )

    mycursor = mydb.cursor()

    sql = 'DROP TABLE IF EXISTS spotify_api.spotify;'
    mycursor.execute(sql)

    sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(client_id="(removed for question)",
                                                           client_secret="(removed for question)"))

    results = sp.search(q='sza', limit=20)

    for idx, track in enumerate(results['tracks']['items']):
        print(idx, track['name'])
        sql = "INSERT INTO spotify_api.spotify (tracks, items) VALUES (" + \
            str(idx) + ", '" + track['name'] + "');"
        mycursor.execute(sql)

    mydb.commit()
 
    print(mycursor.rowcount, "record inserted.")

    mycursor.execute("SELECT * FROM spotify_api.spotify;")

    myresult = mycursor.fetchall()

    for x in myresult:
        print(x)

    mycursor.close()

每次我在VS code终端中运行代码时,都会收到一个错误,指出我的表不存在。它是这样说的: “mysql.connecter.errors.ProgrammingError:1146(42S02):表'spotify_api.spotify'不存在” 我不确定我需要在代码或数据库中修复什么,才能消除这个错误并将数据存储到表中。在我的表中,我创建了两列“tracks”和“items”,但我不确定我的问题是在数据库中还是在代码中。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/158911
 
117 次点击  
文章 [ 1 ]  |  最新文章 9 月前