LoginSignup
4
0

More than 1 year has passed since last update.

sqlalchemy パスワードに@を含む場合の対処方法

Posted at

概要

sqlalchemyとを使用してDBに接続する際に、パスワードに@を含む場合の対処方法です。
パスワードに@が含まれている場合、URLの @ と区別が出来ずエラーになります。

対処方法

quote_plusを使用してパスワードをURLエンコードしてから使用します。
URLエンコードすることでパスワード中の @ が %40 にエンコードされます。

python
from urllib.parse import quote_plus

import pandas as pd
import sqlalchemy as sa

user = 'username'     # ユーザ名
password = 'p@ssword' # パスワード
host = 'localhost'    # ホスト名 or IP
db = 'database'       # データベース
port = 3306           # ポート

# パスワードをURLエンコード p@ssword -> p%40ssword
password = quote_plus(password)
url = f'mysql+pymysql://{user}:{password}@{host}:{port}/{db}?charset=utf8'

# engine作成
engine = sa.create_engine(url, echo=False)

# pandasのread_sql関数にselect文とengineを指定する
query = "select * from table"
df = pd.read_sql(query, con=engine)
4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0