Python Forum

Full Version: insert list into sqlite3
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
#sqlnuff0.py

import sqlite3, time, datetime, random

words = ['foo','bar','moo','soo','noo','boo','fee']

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

def create_db():
    c.execute('CREATE TABLE IF NOT EXISTS foobar(unix REAL, datestamp TEXT, value TEXT)')

def data_entry():
    c.execute("INSERT INTO foobar VALUES(12345,'1-2-2',words)")#my list here should be enough...
    conn.commit()
    c.close()
    conn.close()

def dynamic_data_entry():
    unix = time.time()
    date = str(datetime.datetime.fromtimestamp(unix).strftime('%m-%d'))
    value = random.randrange(0,len(words))
    c.execute("INSERT INTO foobar (unix,datestamp,value) VALUES(?,?,?)",
    (unix, date, value))
    conn.commit()

create_db()
for i in range(10):
    dynamic_data_entry()
c.close()
conn.close()
But I am unable to insert my list into the values column...I am getting a range of numbers, possibly the index values of my elements?
I run your code and it works, inserting ten rows in a new database. What is the error?
I am getting the index values of the elements instead of the actual elements. ie words.index('foo') not 'foo'.

Obviously this is due to my 'value' variable:
value = random.randrange(0,len(words))
I can't think of how to fix that so that I get the elements themselves.
Oh, perhaps you can use
value = words[random.randrange(0,len(words))]
or better
value = random.choice(words)