简体   繁体   中英

Insert Into SQLite DB from Python - “near ”?“: syntax error”

I keep receiving this error, while trying to insert data from Pandas df to SQLite DB: near "?": syntax error . The code snippet looks like this, and in another script, similar idea works fine. My df has 4 columns (int & 3x string), same column names and types are in SQLite table called titles .

conn = sqlite3.connect('test_db_2.db')
c = conn.cursor()

for i in range(len(df)):
    try:
        c.execute("""INSERT INTO titles (?,?,?,?)""",df.iloc[i,:])
        conn.commit()

What could be the cause?

You are missing the VALUES() keyword, which must precede the tuples of values that you want to insert:

INSERT INTO titles VALUES (?, ?, ?, ?)
                 --^--  

I would also recommend enumerating the columns that you want to insert. It is a good practice in SQL since it makes the query easier to understand to those that do not know your data structure, and can allow you to not provide values for all columns:

INSERT INTO titles(col1, col2, col3, col4) VALUES (?, ?, ?, ?)
                --^ -- changae this to your actual column names

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM