首先需要有python库sqlalchemy和psycopg2,如果没有的话可以在python.exe所在目录下打开命令行,输入:
pip install -i https://pypi.douban.com/simple sqlalchemy
pip install -i https://pypi.douban.com/simple psycopg2
接下来的连接语句如下:
from sqlalchemy import create_engine
engine = create_engine('postgresql+psycopg2://user:password@hostname/database_name')
其中user表示数据库的用户,password表示连接数据库的密码,hostname可以用localhost,databasee_name用你连接的数据库的名字,以下是一个示例:
import os
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():
flights = db.execute("SELECT origin, destination, duration FROM flights").fetchall()
for flight in flights:
print(f"{flight.origin} to {flight.destination}, {flight.duration} minutes.")
if __name__ == "__main__":
main()