【问题标题】:how to read from csv file and store data in sqlite3 using python如何使用 python 从 csv 文件中读取数据并将数据存储在 sqlite3 中
【发布时间】:2018-09-01 12:30:37
【问题描述】:

我有一个 Python 类 readCSVintoDB,它从 csv 文件 读取数据并将数据存储到 sqlite 3 数据库

注意: csv 文件包含许多字段,所以我只需要其中的 3 个。

到目前为止,我可以使用 pandas 读取 csv 文件并存储到 dataframe 中。但是如何将数据框存储到数据库中。

错误显示:

文件“C:\Users\test\Documents\Python_Projects\readCSV_DB.py”,第 15 行, 在 init self.importCSVintoDB() 文件中 “C:\Users\test\Documents\Python_Projects\readCSV_DB.py”,第 60 行,在 importCSVintoDB INSERT INTO rduWeather VALUES (?,?,?,?)''', i)

sqlite3.IntegrityError: 数据类型不匹配

当我尝试在 for 循环中打印 i 时,它会显示标题名称 date

读取CSV_DB:

   import sqlite3


    import pandas as pd
    import os

    class readCSVintoDB():

        def __init__(self):
            '''
            self.csvobj = csvOBJ
            self.dbobj = dbOBJ
            '''

            self.importCSVintoDB()

        def importCSVintoDB(self):

            userInput= input("enter the path of the csv file: ")
            csvfile = userInput
            df = pd.read_csv(csvfile,sep=';')

            #print("dataFrame Headers is {0}".format(df.columns))# display the Headers

            dp = (df[['date','temperaturemin','temperaturemax']])
            print(dp)

            '''
            check if DB file exist 
            if no create an empty db file
            '''
            if not(os.path.exists('./rduDB.db')):
                open('./rduDB.db','w').close()

            '''
            connect to the DB and get a connection cursor
            '''
            myConn = sqlite3.connect('./rduDB.db')
            dbCursor = myConn.cursor()

            '''
            Assuming i need to create a table of (Name,FamilyName,age,work)
            '''
            dbCreateTable = '''CREATE TABLE IF NOT EXISTS rduWeather 
                               (id INTEGER PRIMARY KEY, 
                                  Date varchar(256),
                                   TemperatureMin FLOAT,
                                   TemperatureMax FLOAT)'''

            dbCursor.execute(dbCreateTable)
            myConn.commit()


            '''
            insert data into the database
            '''
            for i in dp:
print(i)
                dbCursor.execute('''
                                  INSERT INTO  rduWeather VALUES (?,?,?,?)''', i)

            #myInsert=dbCursor.execute('''insert into Info ('Name','FA','age','work')
                                         #VALUES('georges','hateh',23,'None')''')
            myConn.commit()

            mySelect=dbCursor.execute('''SELECT * from rduWeather WHERE (id = 10)''')
            print(list(mySelect))
            myConn.close()        



    test1 = readCSVintoDB()

【问题讨论】:

  • 我不明白。你显然已经做了一些研究来让你走到这一步,你到底在努力前进的哪个部分?在 sqlite3 和参数化查询中有很多关于 INSERT 的材料。您是否面临特定问题?
  • 如何将检索到的data-frame导入sqlite3数据库?
  • 阅读教程?
  • 如果我从教程中得到答案,我不会在这里问问题
  • 但是你没有在你的问题中尝试过 anything。请说明您尝试了什么以及出了什么问题。没有教程会为您的问题提供准确的答案,但这并不意味着您不能尝试使其适应您的问题。

标签: python pandas csv dataframe sqlite


【解决方案1】:

在您的版本之后,我现在看到了问题。您在 for 循环之外提交 SQL 查询。

编码:

for i in dp:
    dbCursor.execute(''' INSERT INTO rduWeather VALUES (?,?,?,?)''', i) 
    myConn.commit()

【讨论】:

  • 仍然无法正常工作,我将编辑我的问题并添加显示的错误
【解决方案2】:

如果你想写一行(例如:reg = (...))试试这个函数:

def write_datarow(conn, cols, reg):
    ''' Create a new entry (reg) into the rduWeather table

        input:  conn (class SQLite connection)
        input:  cols (list)
                Table columns names
        input:  reg (tuple)
                Data to be written as a row
    '''

        sql = 'INSERT INTO rduWeather({}) VALUES({})'.format(', '. join(cols),'?, '*(len(cols)-1)+'?') 
        cur = conn.cursor()
        # Execute the SQL query 
        cur.execute(sql, reg)
        # Confirm  
        conn.commit()
        return   

但如果你有多行 reg = [(...),...,(...)] 然后使用:

def write_datarow(conn, cols, reg):
    ''' Create a new entry (reg) into the rduWeather table

        input:  conn (class SQLite connection)
        input:  cols (list)
                Table columns names
        input:  reg (list of tuples)
                List of rows to be written
    '''

        sql = 'INSERT INTO rduWeather({}) VALUES({})'.format(', '. join(cols),'?, '*(len(cols)-1)+'?') 
        cur = conn.cursor()
        # Execute the SQL query 
        cur.executemany(sql, reg)
        # Confirm  
        conn.commit()
        return   

【讨论】:

    猜你喜欢
    • 2018-12-01
    • 1970-01-01
    • 2019-09-30
    • 1970-01-01
    • 2019-09-21
    • 2015-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多