python - 为 CSV Sqlite Python 脚本提供的绑定(bind)数量不正确

标签 python sqlite csv insert

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

最佳答案

看来你正试图在这里重新发明轮子:)

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

关于python - 为 CSV Sqlite Python 脚本提供的绑定(bind)数量不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6545847/

相关文章:

python - 如何使用 np.where 使用先前的行创建新列?

python - 为什么 abs() 函数适用于 Python 中的位置坐标?

iphone - 从 sqlite 数据库中查找列中的最大值

SQlite 连接选择语句

python - 如何解析这个逗号分隔值列表

mysql - 将 Excel CSV 导入 MySQL 关系数据库?

python - 如果字符串仅包含来自特定代码页的字符,如何检查 python?

python - 在 python 2.4 中,如何使用 csh 而不是 bash 执行外部命令?

java - 如何有效解析模型对象中的一对多关系?

windows - 使用具有空值的命令按三列对 csv 文件进行排序?