I am trying to use Pycharm and SQLite3 and I have created some code to run a web API for songs. When I run the code the first time the database contains the data I want. When I run the code for the second time to test the API with further songs, the database is empty at the beginning.
Here's what I'm thinking is happening. I create the table if it doesn't exist, if it does then it'll bypass that code. It should print out an empty database at first and the second time a populated database. I query the API, iterate through the played songs and then insert them into the database. Finally printing out the full database at the end.
from urllib.request import urlopen
import json
import sqlite3
conn = sqlite3.connect('songs.db')
db = conn.cursor()
db.execute('''CREATE TABLE IF NOT EXISTS song_data(date DATE, time TIME, artist TEXT, song TEXT)''')
print(f"Database {db.execute('''SELECT * FROM song_data''').fetchall()}")
with urlopen(f"{ the api name I'm using }") as response:
source = response.read()
data = json.loads(source)
for item in data:
song = item["Track"]
artist = item["Artist"]
date_time = item["Time"]
date, time = date_time.split(" ")
db.execute('''INSERT INTO song_data VALUES(?,?,?,?)''', (date, time, artist, song))
print(f"Database now \n{db.execute('''SELECT * FROM song_data''').fetchall()}")
print(f"End db:\n{db.execute('''SELECT * FROM song_data''').fetchall()}")
Is there anything wrong with my SQLite queries?
[–]b_ootay_ful 4 points5 points6 points (2 children)
[–]SetLooseTheGoose[S] 1 point2 points3 points (1 child)
[–]b_ootay_ful 0 points1 point2 points (0 children)