【发布时间】:2020-05-19 23:07:22
【问题描述】:
尝试使用 python 将这个 .csv 导入 sqlite 并得到一个错误:
import csv, sqlite3
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("CREATE TABLE t (ID, LIMIT_BAL, SEX, EDUCATION, MARRIAGE, AGE, PAY_0, PAY_2, PAY_3, PAY_4, PAY_5, PAY_6, BILL_AMT1, BILL_AMT2, BILL_AMT3, BILL_AMT4, BILL_AMT5, BILL_AMT6, PAY_AMT1, PAY_AMT2, PAY_AMT3, PAY_AMT4, PAY_AMT5, PAY_AMT6, Default);")
with open('C:\\Users\\Joseph\\Desktop\\W7\\UCI_Credit_Card.csv','rb') as fin:
dr = csv.DictReader(fin)
to_db = [(i['col1'], i['col2']) for i in dr]
cur.executemany("INSERT INTO t (col1, col2) VALUES (?, ?);", to_db)
con.commit()
con.close()'''
错误:>>> ================ 重启:C:/Users/Joseph/Desktop/W7/Wk7test.py ================ 回溯(最近一次通话最后): 文件“C:/Users/Joseph/Desktop/W7/Wk7test.py”,第 5 行,在 cur.execute("创建表 t (ID, LIMIT_BAL, SEX, EDUCATION, MARRIAGE, AGE, PAY_0, PAY_2, PAY_3, PAY_4, PAY_5, PAY_6, BILL_AMT1, BILL_AMT2, BILL_AMT3, BILL_AMT4, BILL_AMT5, BILL_AMT6, PAY_AMT1, PAY , PAY_AMT4, PAY_AMT5, PAY_AMT6, 默认);") sqlite3.OperationalError:接近“默认”:语法错误
【问题讨论】:
-
default是 SQLite 关键字:sqlite.org/lang_keywords.html 您需要重命名该列。 -
重命名列并将 'rb' 更改为 'r' 以修复文本错误,但现在得到: Traceback(最近一次调用最后一次):文件“C:\Users\Joseph\Desktop\W7\Wk7test .py",第 11 行,在
to_db = [(i['col1'], i['col2']) for i in dr] 文件 "C:\Users\Joseph\Desktop\W7\Wk7test.py ",第 11 行,在 to_db = [(i['col1'], i['col2']) for i in dr] KeyError: 'col1'