Fred_Alb
Fred_Alb

Reputation: 174

Inserting strings to a table in a loop

Hi I'm trying to create tables in sqlite via sqlite3 in python3. The code I got so far is:

import sqlite3
text="hello"
db = sqlite3.connect('C:/DB.db')
c = db.cursor()
c.execute("CREATE TABLE %s (sida)" % name)
for i in range(10):
    c.execute("INSERT INTO %s VALUES (%s)" % (name, str(text))) # This does not work
db.commit()
db.close()
c.close

Changing the value from str(text) to i works;

c.execute("INSERT INTO %s VALUES (%s)" % (name, i))         # This works

Passing an integer as the value works but not a string. I've been trying to find a solution but I'm stuck.

The error I get is:

c.execute("INSERT INTO %s VALUES (%s)" % (name, str(text))) sqlite3.OperationalError: near "a2": syntax error

Upvotes: 0

Views: 120

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521194

You should be using a prepared statement for your inserts, binding values to any placeholders which exist:

c = db.cursor()
c.execute("CREATE TABLE %s (sida)" % name)
for i in range(10):
    c.execute("INSERT INTO %s VALUES (?)" % name, (str(text),))
db.commit()
db.close()
c.close

Actually, it would also be better to not make the table name itself dynamic.

Upvotes: 1

Related Questions