Search code examples
pythonsyntax-erroroperationalerror

How can I insert data from this loop in sqlite


I am trying to insert data from a loop that is similar to this.

import sqlite3
conn = sqlite3.connect('database.db')
c = conn.cursor()

words = ["apple", "banana", "cherry"]
for word in words:
     c.execute("insert into Words (word), values (?)",(word))
     print(word) 
     conn.commit

c.close()
conn.close()

Expected result is similar to this:

enter image description here

I am getting an error. But I am not sure how to correctly format this code right.

The error:

Traceback (most recent call last):
  File "file.py", line 7, in <module>
    c.execute("insert into Words (word), values (?)",(word))
sqlite3.OperationalError: near ",": syntax error

Solution

  • wrong list : commit() not commit because it is a method "insert into Words (word) values (?)",(word,) not "insert into Words (word), values (?)",(word)

    right code is:

    import sqlite3
    conn = sqlite3.connect('database.db')
    c = conn.cursor()
    
    words = ["apple", "banana", "cherry"]
    for word in words:
        c.execute("insert into Words (word) values (?)",(word,))
        print(word) 
    conn.commit()
    conn.close()
    

    Don't worry, happy codding