Python Forum
insert list into sqlite3 - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: insert list into sqlite3 (/thread-7516.html)



insert list into sqlite3 - mepyyeti - Jan-14-2018

#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?


RE: insert list into sqlite3 - Gribouillis - Jan-14-2018

I run your code and it works, inserting ten rows in a new database. What is the error?


RE: insert list into sqlite3 - mepyyeti - Jan-15-2018

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.


RE: insert list into sqlite3 - Gribouillis - Jan-15-2018

Oh, perhaps you can use
value = words[random.randrange(0,len(words))]
or better
value = random.choice(words)