CSV Sqlite Python脚本绑定数量不正确
我正在尝试用一个Python脚本往我的sqlite表里插入数据。
之前一切都运行得很好,直到我想添加一个叫做'information'的新列,这时出现了以下错误:
You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings
于是我添加了:
conn.text_factory = str
然后我又遇到了这个错误:
Incorrect number of bindings supplied. The current statement uses 7, and there are 3 supplied.
我觉得问题可能出在这个新的'information'列上,因为它包含了几行文本,所以我可能把它的类型指定错了,写成了'text'。我的Python脚本代码是:
import sqlite3;
from datetime import datetime, date;
import time
conn = sqlite3.connect('mynewtable.sqlite3')
conn.text_factory = str
c = conn.cursor()
c.execute('drop table if exists mynewtable')
c.execute('create table mynewtable(id integer primary key autoincrement, rank integer, placename text, information text, nooftimes integer, visit text, fav integer, year integer)')
def mysplit (string):
quote = False
retval = []
current = ""
for char in string:
if char == '"':
quote = not quote
elif char == ',' and not quote:
retval.append(current)
current = ""
else:
current += char
retval.append(current)
return retval
# Read lines from file, skipping first line
data = open("mynewtable.csv", "r").readlines()[1:]
for entry in data:
# Parse values
vals = mysplit(entry.strip())
# Insert the row!
print "Inserting %s..." % (vals[0])
sql = "insert into mynewtable values(NULL, ?, ?, ?, ?, ?, ?, ?)"
c.execute(sql, vals)
# Done!
conn.commit()
1 个回答
1
看起来你有点想要重新发明轮子呢 :)
试试用Python的csv模块吧;我用过很多次,效果非常好:http://docs.python.org/library/csv.html
它能很好地处理格式正确的csv文件,尤其是那些包含多行文本的文件。
补充:
比如,你可以直接在你的执行函数中使用csv的行(这些行是列表):
import csv
for row in csv.reader(open('allnamesallyearsn.csv')):
c.execute(sql, row)
第二次补充:
根据我之前的评论,这里是你发布的代码,使用了csv模块:
import sqlite3, csv, time
from datetime import datetime, date
conn = sqlite3.connect('mynewtable.sqlite3')
conn.text_factory = str
c = conn.cursor()
c.execute('drop table if exists mynewtable')
c.execute('create table mynewtable('
'id integer primary key autoincrement, '
'rank integer, '
'placename text, '
'information text, '
'nooftimes integer, '
'visit text, '
'fav integer, '
'year integer)')
sql_insert = "insert into mynewtable values(NULL, ?, ?, ?, ?, ?, ?, ?)"
csv_reader = csv.reader(open('mynewtable.csv', 'rb'))
csv_reader.next() # skip headers
for csv_row in csv_reader:
print "Inserting %s..." % (csv_row)
c.execute(sql_insert, csv_row)
conn.commit()