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
  • Column names can not be parameters in SQL insert/update/delete/... statements, but you can build the string in Python, e.g. with concatenation, formatting, f-strings, ... Commented Jul 27, 2021 at 12:27
  • Does this answer your question? Variable column name in SQL lite and Python Commented Jul 27, 2021 at 12:34
  • Example of building a statement with multiple columns: stackoverflow.com/questions/39140963 Commented Jul 27, 2021 at 12:35

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()

Sign up to request clarification or add additional context in comments.

3 Comments

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.
I just extended the existing problem statement as raised by @buckoii and its self-explanatory and tested.
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.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.