Connect with Google Cloud MySQL through Python; how to access table?

775 views Asked by At

After following this tutorial, I am able to run a script that prints all the details of my database. However, I have no clue as to how to do something with said database! Here's my code:

from google.oauth2 import service_account
import googleapiclient.discovery
import json

SCOPES = ['https://www.googleapis.com/auth/sqlservice.admin']
SERVICE_ACCOUNT_FILE = 'credentials.json'
credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)
sqladmin = googleapiclient.discovery.build('sqladmin', 'v1beta4', credentials=credentials)
response = sqladmin.instances().list(project='single-router-309308').execute()
print(json.dumps(

response, sort_keys=True, indent=2))
sqladmin.close()

Which prints all the info. I tried various things to reach my table, products, but I can't get it to work and keep getting a AttributeError: 'Resource' object has no attribute 'execute' (or 'list') exception. I tried stuff like this:

response = sqladmin.projects().list().execute()

To view my tables as well, but it doesn't work. I believe this is the correct approach since I can connect, but I haven't figured it out yet. Anybody know the answer?

1

There are 1 answers

3
Daniel Redgate On

As per the documentation, you should be able to get access to your table using the below code.

Note that you have an sql project, then an instance on the project, then a database in the instance, then your table is nested inside that database.

from pprint import pprint

# Project ID of the project that contains the instance.
project = 'single-router-309308'

# Database instance ID. You should have this from the above printout
instance = 'my-instance' 

# Name of the database in the instance. You can look this up if you arent sure by logging into google cloud for your project. Your table is inside this database.
database = 'my-database'

request = service.databases().get(project=project, instance=instance, database=database)
response = request.execute() #returns a dictionary with the data

pprint(response)

I would suggest you take a look at the REST API references for CLoud SQL for MySQL for further reading (https://cloud.google.com/sql/docs/mysql/admin-api/rest/v1beta4/databases/get).