Import CSV to database using sqlalchemy

后端 未结 1 1412
误落风尘
误落风尘 2020-12-17 20:10

I am using this example to upload a csv file into a sqlite database:

this is my code:

from numpy import genfromtxt
from time import time
from datetim         


        
相关标签:
1条回答
  • 2020-12-17 21:00

    Are you familiar with Pandas Dataframe?

    Really simple to use (and debug)

    pandas.read_csv(file_name)

    In [5]: pandas.read_csv('/tmp/csvt.csv')
    Out[5]: 
               Name Shack     DB  Payments         Status
    0  Loyiso Dwala  I156  13542        37  LightsOnly ON
    1  Attwell Fayo  I157  13077        32       LightsON
    2  David Mbhele   G25  13155        33       LightsON
    

    For inserting the DataFrames data into a table, you can simply use pandas.DataFrame.to_sql

    So your main code will end up looking something like this:

    engine = create_engine('sqlite:///cdb.db')
    Base.metadata.create_all(engine)
    
    file_name = 'client_db.csv'
    df = pandas.read_csv(file_name)
    df.to_sql(con=engine, index_label='id', name=cdb1.__tablename__, if_exists='replace')
    

    You should read further in the documentation link I added, and set the function Parameters as suits your purpose (specially look at - if_exists, index, index_label, dtype)

    0 讨论(0)
提交回复
热议问题