python从csv文件中读取数据添加到数据库中

示例如下,

其中csv是python内置的一个模块,专门用来处理csv文件的读写,不需要再另外下载。

:origin和:destination以及:duration都是占位符,后面的字典表示用o取代origin占位符来执行sql语句

import csv

from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker

engine = create_engine('postgresql+psycopg2://postgres:88595073@localhost/lecture3')
db = scoped_session(sessionmaker(bind=engine))

def main():
    f = open("flights.csv")
    reader = csv.reader(f)
    for o, dest, dur in reader:
        db.execute("INSERT INTO flights (origin, destination, duration) VALUES (:origin, :destination, :duration)",
                    {"origin": o, "destination": dest, "duration": dur})
        print(f"Added flight from {o} to {dest} lasting {dur} minutes.")
    db.commit()

if __name__ == "__main__":
    main()

 

你可能感兴趣的:(python)