1

I am trying to use sqlite3 in Python by using a for loop to iterate through all the items in a list and populate a column with that data. My code below will hopefully shed some light on the problem:

import sqlite3 as lite

test_run = ['tommy', 'olga', 'peter', 'lulu']


con = lite.connect("test.db")
cur = con.cursor()
cur.execute('DROP TABLE IF EXISTS test1;')
cur.execute('CREATE TABLE test1(symbol TEXT); ')
for i in test_run:
    name = i
    print name

cur.executemany('INSERT INTO test1 VALUES(?)',name)

with con:

cur = con.cursor()
cur.execute("SELECT * FROM test1")

rows = cur.fetchall()

for row in rows:
     print row

I apologize if this is very basic, but I have just learned Python and this is my first time using SQL. When I print name it seems like this should work but when using fetchall to see what is being populated it appears as:

(u't',)
(u'o',)
(u'm',)
(u'm',)
(u'y',)
(u'o',)
(u'l',)

I have read a lot of the answers here and this would seem to be the correct way to accomplish this.

1 Answer 1

0

I can identify following issues in your code.

  1. The cur.executemany is not in the loop.
  2. There is only one parameter to bind in the insert query. No need to use cur.executemany.
  3. When binding string parameter to a query, you should convert your string to tuple.

I think the correct code might look like this -

for i in test_run:
    name = (i,)
    print i
    cur.execute("INSERT INTO test1 VALUES(?)", name)

Also use con.commit() after the insert query or you can't get the inserted rows after application termination. Hope this helps.

Sign up to request clarification or add additional context in comments.

1 Comment

Yours should work, but retaining the executemany is good practice for large datasets.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.