Open Tobotobo opened 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)
接続情報を環境変数で設定する場合
settings.env
パスワードを都度入力する場合