0
import pandas as pd
import sqlite3

df = pd.read_csv('liked_songs.csv')
!sqlite3 spotify.db < spotify.sql
connection = sqlite3.connect('spotify.db')
df.columns = df.columns.str.replace(' ','_')
cursor = connection.cursor()

for index in df.index:
    sr = df.iloc[index]
    cursor = cursor.execute(f"""INSERT INTO spotify (SpotifyID, ArtistID, Track_Name, 
                           Album_Name, Artist_Name, Release_Date, Duration,Popularity, Genres)
                        VALUES ('{sr.SpotifyID}', '{sr.Artist_ID}', '{sr.Track_Name}', 
                                '{sr.Album_Name}', '{sr.Artist_Name}', '{sr.Release_Date}',
                                '{sr.Duration}', '{sr.Popularity}', '{sr.Genres}')""")

I'm using pandas to import a .csv file and sqlite3 to enter data into a database made from a SQL script.Image of SQL script

ompanos
  • 1
  • 1
  • 1
    Probably one of the values contains an embedded quote. This is why you should always use [parameter subtitution](https://stackoverflow.com/questions/902408/how-to-use-variables-in-sql-statement-in-python) when passing values to `cursor.execute`. – snakecharmerb Apr 24 '22 at 08:28

1 Answers1

0

You can directly use to_sql:

import pandas as pd
import sqlite3

df = pd.read_csv('liked_songs.csv')
connection = sqlite3.connect('spotify.db')
df.columns = df.columns.str.replace(' ','_')
df.to_sql('spotify', connection, if_exists='replace', index=None)
Corralien
  • 109,409
  • 8
  • 28
  • 52