INPUT FILE:
$ cat inputs.csv
'18-01-2019', 296.0
'18-01-2019', 296.0
'18-01-2019', 296.0
CODE:
import csv
import sqlite3
import pprint
conn = sqlite3.connect('metrics.db')
c = conn.cursor()
def read_file(filename):
with open(filename, 'r') as f:
yield from f
for row in read_file('inputs.csv'):
data = row.split(',')
values = '({}, {})'.format(data[0], data[1].strip())
print('Values are: {}'.format(values))
try:
query = '\'INSERT INTO metric_db VALUES (?, ?)\', {}'.format(values)
print('Query is: {}'.format(query))
c.execute(query)
except sqlite3.IntegrityError as e:
pass
conn.commit()
conn.close()
OUTPUT ERROR:
Values are: ('18-01-2019', 296.0)
Query is: 'INSERT INTO metric_db VALUES (?, ?)', ('18-01-2019', 296.0)
Traceback (most recent call last):
File "write_to_db.py", line 21, in <module>
c.execute(query)
sqlite3.OperationalError: near "'INSERT INTO metric_db VALUES (?, ?)'": syntax error
I thought this was easier. Quite a few SO threads on this error. But I am still not there yet :(
Change your query statement:
query = 'INSERT INTO metric_db VALUES {}'.format(values)
EDIT
To Avoid SQL injection and use correct date format:
import csv
import sqlite3
import pprint
from datetime import datetime
conn = sqlite3.connect('metrics.db')
c = conn.cursor()
def read_file(filename):
with open(filename, 'r') as f:
yield from f
for row in read_file('inputs.csv'):
data = row.split(',')
values = '({}, {})'.format(data[0], data[1].strip())
print('Values are: {}'.format(values))
date_readed = datetime.strptime(data[0], '%d-%m-%Y').strftime('%Y-%m-%d')
try:
query = 'INSERT INTO metric_db VALUES (?, ?)'
c.execute(query,(date_readed,data[1],))
except sqlite3.IntegrityError as e:
pass
conn.commit()
conn.close()
Check your schema.sql file. just try to copy-paste this file from tutorial.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.