Create a TCP connection to Cloud SQL for MySQL by using SQLAlchemy.
Documentation pages that include this code sample
To view the code sample used in context, see the following documentation:
- Connecting from App Engine flexible environment to Cloud SQL
- Connecting from App Engine standard environment to Cloud SQL
- Connecting from Cloud Functions to Cloud SQL
- Connecting from Cloud Run to Cloud SQL
- Connecting Overview
- Connecting using the Cloud SQL Auth proxy
- Managing database connections
# Remember - storing secrets in plaintext is potentially unsafe. Consider using # something like https://cloud.google.com/secret-manager/docs/overview to help keep # secrets secret. db_user = os.environ["DB_USER"] db_pass = os.environ["DB_PASS"] db_name = os.environ["DB_NAME"] db_host = os.environ["DB_HOST"] # Extract host and port from db_host host_args = db_host.split(":") db_hostname, db_port = host_args, int(host_args) pool = sqlalchemy.create_engine( # Equivalent URL: # mysql+pymysql://<db_user>:<db_pass>@<db_host>:<db_port>/<db_name> sqlalchemy.engine.url.URL.create( drivername="mysql+pymysql", username=db_user, # e.g. "my-database-user" password=db_pass, # e.g. "my-database-password" host=db_hostname, # e.g. "127.0.0.1" port=db_port, # e.g. 3306 database=db_name, # e.g. "my-database-name" ), **db_config )
To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.