我尝试使用python脚本将值插入到我的sqlite表中。为CSV Sqlite Python脚本提供的绑定数量不正确
它是完美的工作,直到我试图添加一个名为“信息”的另一列 - 它然后把下面的错误:
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'列包含几行te xt所以我可能会错误地将其指定为'文本'。我的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()
您可以发布代码块而不是只创建表的那一行吗? – 2011-07-01 09:14:55
是的,对不起,我已经添加了完整的脚本。我应该最初发布它,抱歉,谢谢! – medley
请参阅我的答案中的第二个编辑,了解使用csv模块的重新编译的程序版本。 – 2011-07-03 20:10:16