Tobotobo / my_knowledge_base

0 stars 0 forks source link

Python で PostgreSQL に接続し結果を DataFrame で取得する #16

Open Tobotobo opened 4 months ago

Tobotobo commented 4 months ago

接続情報を環境変数で設定する場合

pip install psycopg2-binary SQLAlchemy pandas python-dotenv
import os, sqlalchemy, dotenv, pandas
dotenv.load_dotenv("./settings.env", override=True)
db_host=os.getenv("DB_HOST")
db_port=os.getenv("DB_PORT")
db_name=os.getenv("DB_NAME")
db_username=os.getenv("DB_USERNAME")
db_password=os.getenv("DB_PASSWORD")
engine = sqlalchemy.create_engine(f"postgresql://{db_username}:{db_password}@{db_host}:{db_port}/{db_name}")
df = pandas.read_sql_query("SELECT * FROM example", engine)
display(df)

settings.env

DB_HOST=localhost
DB_PORT=5432
DB_NAME=postgres
DB_USERNAME=postgres
DB_PASSWORD=postgres

パスワードを都度入力する場合

pip install psycopg2-binary SQLAlchemy pandas
from sqlalchemy import create_engine
import pandas as pd
from getpass import getpass

# パスワード入力
password = getpass()

# 接続
engine = create_engine(f"postgresql://username:{password}@localhost:5432/dbname")

# SQL を実行し DataFrame を取得
df = pd.read_sql_query("SELECT * FROM example", engine)