tech.chakapoko.com
Home / Python / DB

[Python]SQLAlchemyでMySQLに接続する

sqlalchemy + mysqlclient で接続する

$ pip install sqlalchemy mysqlclient
from sqlalchemy import create_engine, text

engine = create_engine('mysql://<user>:<password>@<host>[:<port>]/<dbname>')

q = text("SELECT @@VERSION")
rs = engine.execute(q)

for row in rs:
    print(row[0])

sqlalchemy + mysql-connector-python で接続する

$ pip install sqlalchemy mysql-connector-python
from sqlalchemy import create_engine, text

engine = create_engine('mysql+mysqlconnector://<user>:<password>@<host>[:<port>]/<dbname>')

q = text("SELECT @@VERSION")
rs = engine.execute(q)

for row in rs:
    print(row[0])