1

Could you tell me what I am doing wrong in the code?

I've tried to search for this particular case and could not find the answer. I've also tried to use example from the official docs on sqlite3, but couldn't get it to work. Basically, I have a lot of data in inc_data that I need to insert into sqlite3.

import sqlite3

inc_data = [[u'Period Ending', u'Dec 31, 2012', u'Dec 31, 2011', u'Dec 31, 2010'],
            [u'Total Revenue\n', u'104,507,000\n', u'106,916,000\n', u'99,870,000\n'],
            ]


conn = sqlite3.connect("inc_data.db")
c = conn.cursor()
c.execute('''DROP TABLE inc_table''')

c.execute('''CREATE TABLE inc_table
             (item text, value1 text, value2 text, value3 text)''')

c.execute('INSERT INTO inc_table VALUES (?,?,?,?)', inc_data)

conn.commit()

conn.close()

The error msg:

c.execute('INSERT INTO inc_table VALUES (?,?,?,?)', inc_data)
sqlite3.OperationalError: no such table: inc_table

many thanks for your help.

vt2424253
  • 1,387
  • 4
  • 25
  • 39

1 Answers1

3

You passed in two items; each a list of parameters.

Either use c.executemany() (which does expect a sequence of sequences), or loop over inc_data to give c.execute() one set of bind values:

# insert multiple rows; one for each entry in `inc_data`
c.executemany('INSERT INTO inc_table VALUES (?,?,?,?)', inc_data)

# or loop
for bind_values in inc_data:
    c.execute('INSERT INTO inc_table VALUES (?,?,?,?)', bind_values)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • c.executemany works perfectly. Thanks so much for showing me both methods. I really appreciate your help. – vt2424253 Oct 21 '13 at 18:02