2011-07-01 48 views
1

我尝试使用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() 
+0

您可以发布代码块而不是只创建表的那一行吗? – 2011-07-01 09:14:55

+0

是的,对不起,我已经添加了完整的脚本。我应该最初发布它,抱歉,谢谢! – medley

+0

请参阅我的答案中的第二个编辑,了解使用csv模块的重新编译的程序版本。 – 2011-07-03 20:10:16

回答

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) 

2日编辑:

按我的最后一条评论,这里是您使用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() 
+0

哈哈谢谢!我倾向于尝试重新发明轮子。该文档很好,但我不确定如何实现它,该模块的输出会给我一个sqlite数据库吗?感谢您的建议! – medley

+0

我试过并得到'NameError:name'sql'未定义' – medley

+0

是的我的意思是纯粹是一个关于csv模块如何为每个记录提供正确解析的例子,因此您不必费心解释直接自己的CSV文件。我会用你的程序编辑我的帖子(尽管我不保证它会被编译,甚至更少的工作,因为我只是试图把我的例子放在你的上下文中)。 – 2011-07-03 18:10:00

相关问题