【发布时间】:2011-07-01 09:08:51
【问题描述】:
我正在尝试使用 python 脚本将值插入到我的 sqlite 表中。
在我尝试添加另一个名为“信息”的列之前,它一直运行良好 - 然后它引发了以下错误:
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.
我认为问题在于这个新的“信息”列包含几行文本,因此我可能将其错误地指定为“文本”。我的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()
【问题讨论】:
-
你能发布代码块而不是只创建表格的那一行吗?
-
是的,抱歉,我现在已经添加了完整的脚本。我应该一开始就全部发布,抱歉,谢谢!
-
请参阅我的答案中的第二个编辑,以获得使用 csv 模块的程序的重新设计版本。