Python将CSV导入sqlite [英] python import csv to sqlite

查看:170
本文介绍了Python将CSV导入sqlite的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用python tkinter将csv文件导入sqlite3数据库. 我使用askopenfilename对话框打开文件,然后将文件传递给readFile函数.

Hi i am trying to import a csv file to a sqlite3 database using python tkinter. I open file using askopenfilename dialog and pass the file to readFile function.

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.

我尝试了所有可能的解决方案,但无法将文件导入数据库.
我还尝试了这些链接中给出的尝试解决方案
Python CSV到SQLite

I tried every possoible solution available but couldn't import file to database.
I also tried tried solutions given in these links
Importing a CSV file into a sqlite3 database table using Python
Python CSV to SQLite

链接到输入文件输入文件

推荐答案

您需要先打开文件,然后再将其传递给csv.reader.这是一个可行的基本可运行示例.我添加了一个类,以允许按原样使用您现有的方法.

You need to open the file before you pass it to csv.reader. Heres a basic runnable example that works. I added a class to allow your existing methods to be used as is.

import sqlite3
import csv

class csvrd(object):
    def csvFile(self):

        self.readFile('Labels.csv')

    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"
        with open(filename) as f:
            reader = csv.reader(f)
            for field in reader:
                cur.execute("INSERT INTO unicom VALUES (?,?,?,?);", field)

        conn.commit()
        conn.close()

c = csvrd().csvFile()

这篇关于Python将CSV导入sqlite的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆