我已經用 Python 連接到 Spotify 的 API,以提取搜索到的藝術家的前 20 首曲目。我正在嘗試將 MySQL Workbench 中的資料存盤在一個名為“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.connector.errors.ProgrammingError:1146(42S02):表'spotify_api.spotify'不存在”我不確定我需要在我的代碼或我的資料庫中按順序修復什么消除此錯誤并將我的資料存盤到我的表中。在我的表中,我創建了兩列“tracks”和“items”,但我不確定我的問題是出在我的資料庫中還是在我的代碼中。
uj5u.com熱心網友回復:
嗯,看起來很清楚。你跑了
DROP TABLE IF EXISTS spotify_api.spotify;
...
INSERT INTO spotify_api.spotify (tracks, items) VALUES ...
我們甚至不會在這里提到名為little ol' Bobby Tables的 Chuck Berry 曲目的幽靈。
您將其丟棄,然后嘗試將其插入。那是行不通的。您需要在插入之前創建表。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/522264.html
標籤:mysql
上一篇:MySQLPivot和左連接
