我嘗試使用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