您好我正在尝试使用python tkinter将csv文件导入sqlite3数据库 . 我使用askopenfilename对话框打开文件,并将文件传递给readFile函数 .
def csvFile(self):
f1 = askopenfilename()
self.readFile(f1)
def readFile(self, filename):
conn = sqlite3.connect('Unicommerce.db')
cur = conn.cursor()
cur.execute("""CREATE TABLE IF NOT EXISTS unicom(products varchar,channel varchar,regulatory_forms varchar,shipment varchar)""")
filename.encode('utf-8')
print "test1"
reader = csv.reader(filename)
for field in reader:
cur.execute("INSERT INTO unicom VALUES (?,?,?,?);", field)
conn.commit()
conn.close()
我收到了这个错误 .
cur.execute("INSERT INTO unicom VALUES (?,?,?,?);", field)
ProgrammingError: Incorrect number of bindings supplied. The current statement uses 4, and there are 1 supplied.
我尝试了所有可用的可用解决方案,但无法将文件导入数据库 .
我也试过这些链接中给出的尝试解决方案
Importing a CSV file into a sqlite3 database table using Python
Python CSV to SQLite
编辑:链接到输入文件Input File
4 回答
您需要在将文件传递给
csv.reader
之前打开该文件 . 这是一个有效的基本可运行示例 . 我添加了一个类来允许现有方法按原样使用 .execute
可以这样工作:cur.execute("INSERT INTO unicom VALUES (value1,value2, value3,value4);")
其中value1..4
是您数据的正确文本表示 .cur.execute("INSERT INTO unicom VALUES (?, ?, ?, ?);", [value1,value2, value3,value4]
其中value1..4
在list
和db驱动程序中负责正确解释主要数据类型 .好的,因为我无法查看您的数据,我会像下面这样:
使用熊猫:
我想共享一个库,我用它很容易将我的csv转换成sqlite数据库 .
这是csv2sqlite .
在终端运行:csv2sqlite.py [] .
确保您的数据库具有与csv相同的列号 .
希望能帮助到你 .
谢谢 .