输入文件:
$ cat inputs.csv
'18-01-2019', 296.0
'18-01-2019', 296.0
'18-01-2019', 296.0
代码:
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()
输出错误:
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
我认为这比较容易。相当多的SO线程处理此错误。但是我还没到那儿:(
答案 0 :(得分:1)
更改查询语句:
query = 'INSERT INTO metric_db VALUES {}'.format(values)
编辑
要避免SQL注入并使用正确的日期格式:
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()
答案 1 :(得分:0)
检查您的schema.sql文件。只需尝试从教程中复制粘贴此文件即可。