Connect your Python app to Google Cloud SQL the “Easy Way”!
I am drawing these instructions directly from this blog which is an extremely comprehensive and well documented guide on the following process. I would highly recommend going through it.
Lets get into it:
For this example we will be creating and connecting to a MySQL instance, but GC SQL has support for both PostgreSQL and MySQL Server as well.
First install the necessary dependencies via pip install cloud-sql-python-connector sqlalchemy
.
The following parameters are needed to connect properly to a Cloud SQL instance. Change the values to ones that coincide with your instance, and add them into a .env
file if you’d like.
INSTANCE_CONNECTION_NAME
: The connection name to your Cloud SQL Instance takes the formPROJECT_ID:REGION:INSTANCE_NAME
whereinstance_name
is the name of your Google Cloud SQL instance, not your general GCP instance name (I’ve made that mistake).DB_USER
: The user in which the connector will use to connect to the database.DB_PASS
: The password of the DB_USER.DB_NAME
: The name of the database on the Cloud SQL instance to connect to.
Initialize a Connector
object and call its connect
method with the proper input parameters as shown below to connect to Cloud SQL using the connector.
You will use the creator
argument for sqlalchemy.create_engine
to use this connector with SQLAlchemy/
You are now ready to start querying your database. Lets run a test! 🎉 📝
Close the Connector
object's background resources at the end of your code as follows.
And that’s it. Let me know in the comments if you experience any issues and maybe we can figure them out together, or check out the original blog for these steps or the Youtube video for more clarification.