0

I am trying to clean raw json data by parsing and inserting it into a table of an sqlite db.

I have 22 columns in my table and want to find a way of looping through them so I don't need to write 22 loops which insert the data or a single column.

I have simplified the approach I am trying with the following:

import sqlite3

conn = sqlite3.connect('cdata.sqlite')
cur = conn.cursor()

column = 'name'
value = 'test'

cur.execute('''INSERT INTO COMPANY (?)
            VALUES (?)''',(column,),(value,)) 

conn.commit()
conn.close()

This doesn't work at the moment and return the error TypeError: function takes at most 2 arguments (3 given).

Does anyone know if it is possible to write an SQLite insert statement using 2 parameters like this or another way I might be able to iterate through the columns?

3

1 Answer 1

0

Sample as below:

import sqlite3

conn = sqlite3.connect("cdata.sqlite")
cur = conn.cursor()

column = ("name", "age")
table = f"CREATE TABLE IF NOT EXISTS COMPANY ({column[0]} text, {column[1]} text);"

cur.execute(table)

name = "hello"
age = "1"
sql_stmt = f"INSERT INTO COMPANY({column[0]},{column[1]}) VALUES ('{name}', '{age}')"

cur.execute(sql_stmt)

with conn:
    cur.execute("SELECT * FROM COMPANY")
    print(cur.fetchall())

conn.commit()
conn.close()

3
  • Could you elaborate on the workings of your code? You shouldn't rely on passerbys to understand (possibly incorrectly), instead please comment and explain your code, it will be more appealing.
    – joH1
    Jul 27, 2021 at 13:39
  • I just extended the existing problem statement as raised by @buckoii and its self-explanatory and tested. Jul 27, 2021 at 15:10
  • For experienced Python coders knowing database programming yes, the code is readable. For any other person it probably is harder to understand. Anyway a code wall without any explanation or comment is never appealing.
    – joH1
    Jul 28, 2021 at 8:12

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.