我收到一条错误消息说明 ValueError:操作参数必须为str 将数据插入表格
这是我的代码
import csv
import sqlite3
conn = sqlite3.connect('results.db')
curs = conn.cursor()
total = []
headerlist = []
headerlisttype = []
rowindex = 1
def parse_csv():
'''
Adds all the rows in csv file to total list
'''
with open('3-1 RESULTS.csv', 'r') as csvfile:
parser = csv.reader(csvfile)
headerlist = next(parser)
for row in parser:
total.append(row)
# end parse_csv
def create_table():
'''
Creates a table with just auto incremented SNO column
'''
sql = '''CREATE TABLE IF NOT EXISTS RESULTS31
(SNO NUMBER NOT NULL, REGNUMBER NUMBER, NAME TEXT,
MPII TEXT, SP TEXT, CG TEXT, FLAT TEXT, FS TEXT, OS TEXT,
OSLAB TEXT, MPIILAB TEXT, SS TEXT, SGPA REAL, CGPA REAL) '''
curs.execute(sql)
conn.commit()
#end create_table function
def insert_to_table(row):
global rowindex
sno = rowindex
rowindex += 1
reg, name, mpII, sp, cg, flat, fs, os, oslab, mpIIlab, ss, sgpa, cgpa = row
sql = '''INSERT INTO RESULTS31
(SNO NUMBER NOT NULL, REGNUMBER NUMBER, NAME TEXT,
MPII TEXT, SP TEXT, CG TEXT, FLAT TEXT, FS TEXT, OS TEXT,
OSLAB TEXT, MPIILAB TEXT, SS TEXT, SGPA REAL, CGPA REAL) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ''',
(int(sno), int(reg), name, mpII, sp, cg, flat, fs, os, oslab, mpIIlab, ss, float(sgpa), float(cgpa))
try:
curs.execute(sql)
except Exception as e:
print(e)
def print_from_table():
sql = ''' SELECT * FROM RESULTS31 '''
curs.execute(sql)
data = curs.fetchall()
for row in data:
print(row)
parse_csv()
create_table()
for row in total:
insert_to_table(row)
print_from_table()
任何人都可以在我的代码中找到错误 帮助将更加渺茫
答案 0 :(得分:1)
INSERT只需要列名,而不是任何列类型。
execute()
有两个参数,SQL语句文本和SQL参数列表:
sql = '''INSERT INTO RESULTS31 (SNO, REGNUMBER, ...'''
params = (int(sno), ...)
curs.execute(sql, params)
答案 1 :(得分:0)
我从未见过这个Python构造:
sql = '''INSERT INTO RESULTS31 (SNO NUMBER NOT NULL, REGNUMBER NUMBER, NAME TEXT, MPII TEXT, SP TEXT, CG TEXT, FLAT TEXT, FS TEXT, OS TEXT, OSLAB TEXT, MPIILAB TEXT, SS TEXT, SGPA REAL, CGPA REAL) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ''', (int(sno), int(reg), name, mpII, sp, cg, flat, fs, os, oslab, mpIIlab, ss, float(sgpa), float(cgpa))
除非这是格式化字符串的完全有效的语法,否则您的代码将创建一个元组并将其绑定到' sql'
查看format()