Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
insert list into sqlite3
#1
#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?
Reply
#2
I run your code and it works, inserting ten rows in a new database. What is the error?
Reply
#3
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.
Reply
#4
Oh, perhaps you can use
value = words[random.randrange(0,len(words))]
or better
value = random.choice(words)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  sqlite3 Conn Insert Value Error TylerDunbar 3 675 Sep-04-2023, 06:32 PM
Last Post: deanhystad
  store all variable values into list and insert to sql_summary table mg24 3 1,096 Sep-28-2022, 09:13 AM
Last Post: Larz60+
  openpyxl insert list with formulas Irv1n 1 1,516 Sep-16-2021, 08:10 AM
Last Post: Irv1n
  how to insert list into database zubair 2 9,867 Feb-05-2019, 12:16 PM
Last Post: rajesh1997
  Insert list in particular column! Help! vndywarhol 0 2,456 Sep-17-2018, 11:14 PM
Last Post: vndywarhol
  sqlite3 operational error on insert query jonesin1974 5 4,205 Jun-26-2018, 03:31 PM
Last Post: Larz60+
  Insert using psycopg giving syntax error near "INSERT INTO" olgethorpe 4 15,495 Jul-21-2017, 07:39 PM
Last Post: nilamo
  sqlite3 insert issue gohanzdad 1 3,109 May-16-2017, 05:26 PM
Last Post: gohanzdad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020