【问题标题】:Incorrect number of bindings supplied for CSV Sqlite Python script为 CSV Sqlite Python 脚本提供的绑定数量不正确
【发布时间】: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 模块的程序的重新设计版本。

标签: python sqlite csv insert


【解决方案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()

【讨论】:

  • 哈哈谢谢!我确实倾向于尝试重新发明轮子。该文档很棒,但我不确定如何实现它,该模块的输出是否会给我一个 sqlite db?感谢您的建议!
  • 是的,我的意思是这纯粹是一个示例,说明 csv 模块如何为您提供正确解析的每条记录,因此您不必费心自己直接解释 CSV 文件。我会用你的程序编辑我的帖子(虽然我不保证它会编译,甚至更少的工作,因为我只是想把我的例子更多地放在你的上下文中)。
  • 您好,非常感谢!会得到这个工作,真的很感激!
猜你喜欢
  • 2011-06-06
  • 2013-02-09
  • 1970-01-01
  • 2021-06-16
  • 1970-01-01
  • 2012-04-16
  • 2015-12-06
  • 2013-10-28
  • 2021-06-28
相关资源
最近更新 更多