i'm trying to insert values in my table db with a loop for

Question:

import sqlite3

connexion = sqlite3.connect("album2.db")
curseur = connexion.cursor()

#------ Tables

curseur.execute("""CREATE TABLE artiste (
    artiste_id INTEGER NOT NULL PRIMARY KEY, 
    nom VARCHAR);""")
curseur.execute("""CREATE TABLE album (
    album_id INTEGER NOT NULL PRIMARY KEY, 
    artiste_id INTEGER REFERENCES artiste,
    titre VARCHAR,
    annee_sortie INTEGER);""")

#----- Add to db

artiste = ("Micheal Jackson", "Celine Dion", "Luke Combs")
for i in artiste:
    curseur.execute(f"""INSERT INTO artiste (nom) VALUES ({i});""")

connexion.commit()
connexion.close()

ERROR :

line 18, in
curseur.execute("INSERT INTO artiste (nom) VALUES (" + i + ");")
sqlite3.OperationalError: near "Jackson": syntax error

Asked By: Amine Kanem

||

Answers:

Fix

As you building the query manually, the string you pass is the following

INSERT INTO artiste (nom) VALUES (Jackson)

And you can’t give string like this it needs to be quoted

INSERT INTO artiste (nom) VALUES ("Jackson")
for i in artiste:
    curseur.execute(f"""INSERT INTO artiste (nom) VALUES ("{i}");""")

Improve

But the best is to use sql placeholder, for slite it’s with ?

for i in artiste:
    curseur.execute("INSERT INTO artiste (nom) VALUES (?);", (i,))

It does the quoting for yo, and so avoid SQL injection

Answered By: azro
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.