【发布时间】:2020-09-08 18:23:00
【问题描述】:
我正在尝试将 csv 文件加载到我的数据库表中并不断收到此 ProgrammingError:提供的绑定数量不正确。当前语句使用 10,并且提供了 1。我认为这可能与我的 c.execute 有关,但我不确定修复方法是什么。我在下面附上了我的代码,以尝试将 CSV 插入我的单个表中。
我的代码是
import sqlite3
import csv
# creating my first database that will be used for the assignment.
conn = sqlite3.connect('Assignment3.db')
c = conn.cursor()
#Creating table- CCSubset with all of the required fields
c.execute("drop table if exists CCSubset")
c.execute("""CREATE TABLE CCSubset (
CCSubset_id integer not null primary key,
CCSubset_limit int,
CCSubset_sex varchar(10),
CCSubset_edu varchar(10),
CCSubset_marr varchar(10),
CCSubset_age int,
CCSubset_pay int,
CCSubset_bill int,
CCSubset_payamt int,
CCSubset_default int)""")
conn.commit()
f=open('CCSubset.csv')
insert sql = "insert into CCSubset values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
for row in str(csv.reader(f)):
c.execute(insert_sql, row)
我收到的错误是:ProgrammingERROR:提供的绑定数量不正确。当前语句使用 10,提供了 1 个。
这是更新后的代码:
# creating my first database that will be used for the assignment.
conn = sqlite3.connect('Assignment3.db')
c = conn.cursor()
#Creating table- CCSubset with all of the required fields
c.execute("drop table if exists CCSubset")
c.execute("""CREATE TABLE CCSubset (
CCSubset_id integer not null primary key,
CCSubset_limit int,
CCSubset_sex varchar(10),
CCSubset_edu varchar(10),
CCSubset_marr varchar(10),
CCSubset_age integer,
CCSubset_pay int,
CCSubset_bill int,
CCSubset_payamt int,
CCSubset_default int)""")
conn.commit()
f=open('CCSubset.csv')
for row in str(reader):
insert_sql = "insert into CCSubset values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
print(row)
conn.commit()
我现在收到的输出是:
<
c
s
v
.
D
i
c
t
R
e
a
d
e
r
o
b
j
e
c
t
a
t
0
x
7
f
9
b
c
8
0
7
2
4
e
0
>
所以我完全停滞不前,不知道我需要做什么。任何和所有的帮助将不胜感激。
【问题讨论】:
-
解压元组
c.execute(insert_sql, *row)对你有什么帮助吗? -
@AlanHoover 如果我将它插入第一个代码并且如果我插入我尝试的第二组代码,我仍然会收到错误的绑定数量。
-
那个 csv 是什么样的?做一个
print()的行。 -
当我执行 print(row) 并从 str(reader) 中删除执行和 str 但更多行时看起来像这样: OrderedDict([('ID', '1'), ('LIMIT_BAL', '20000'), ('SEX', '2'), ('EDUCATION', '2'), ('MARRIAGE', '1'), ('AGE', '24'), ('PAY', '2'), ('BILL_AMT', '3913'), ('PAY_AMT', '0'), ('DefaultNext', '1')]) OrderedDict([('ID', ' 2'), ('LIMIT_BAL', '120000'), ('SEX', '2'), ('EDUCATION', '2'), ('MARRIAGE', '2'), ('AGE', ' 26'), ('PAY', '-1'), ('BILL_AMT', '2682'), ('PAY_AMT', '0'), ('DefaultNext', '1')])
-
用给出列表而不是字典的那个试试(你没有用
DictReader()打开的那个)