如何使用python从csv文件中读取并在sqlite3中存储数据

时间:2018-03-22 22:16:51

标签: python pandas csv dataframe sqlite

我有一个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时,它会显示标题名称日期

readCSV_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()

2 个答案:

答案 0 :(得分:0)

如果你想写一行(例如: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   

答案 1 :(得分:0)

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

编码:

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