I have a table called 'test' that I'm creating through my Python code.
db = sqlite3.connect("mydb.db")
cur = db.cursor()
cur.execute('''CREATE TABLE IF NOT EXISTS test
(
"id" text primary key,
"field1" integer,
"fiedl2" integer,
"field3" text
)'''
)
I have a file where each line is a json. I read the file line by line and insert data from the json of each line into the table.
file.txt:
{'id':'abcde', 'field1': 10, 'field2': 20, 'field3': "hello"}
{'id':'asdf', 'field1': 20, 'field2': 5, 'field3': "world"}
{'id':'qwerty', 'field1': 1, 'field2': 2, 'field3': None}
If a field in the json doesn't have a value, I want to insert null into my sqlite table. So as in the last line above, if field3 doesn't have a value, I put None into it because this is what I read in other related questions.
However, when I insert as below:
for line in readfile:
line = ast.literal_eval(line)
columns = '", "'.join([i.strip() for i in line.keys()])
columns = "\"" + columns + '\"'
placeholders = ', '.join('?' * len(line))
sql = 'INSERT INTO test ({}) VALUES ({})'.format(columns, placeholders)
cur.execute(sql, ["'" + str(i) + "'" for i in line.values()])
db.commit()
I get 'None' instead of null when I perform a select statement from the Sqlite console.
sqlite> select * from test where id='qwerty' limit 1;
'qwerty'|1|2|'None'|
Can anyone please help me fix this? I'm using Python 3.4
None?