簡體   English   中英

如何使用python從csv文件讀取並將數據存儲在sqlite3中

[英]how to read from csv file and store data in sqlite3 using python

我有一個python類readCSVintoDB ,它從csv文件讀取並將數據存儲到sqlite 3數據庫中

注意:csv文件包含許多字段,所以我只需要3個即可。

到現在為止,我已經能夠讀取csv文件並使用pandas存儲到dataframe中。 但是如何將數據框存儲到數據庫中。

顯示的錯誤:

文件“ C:\\ Users \\ test \\ Documents \\ Python_Projects \\ readCSV_DB.py”, init self.importCSVintoDB()文件“ C:\\ Users \\ test \\ Documents \\ Python_Projects \\ readCSV_DB.py”,行60 importCSVintoDB插入rduWeather值(?,?,?,?)''',i)

sqlite3.IntegrityError:數據類型不匹配

當我嘗試在for循環中打印時,它顯示標題名稱日期

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

如果要寫一行(例如: 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   

在您的版本發行后,我看到了問題。 您在for循環外提交SQL查詢。

編寫此代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM