首页 > 解决方案 > 通过 Python 连接 Google Cloud MySQL;如何访问表?

问题描述

遵循本教程后,我可以运行一个脚本来打印我的数据库的所有详细信息。但是,我不知道如何处理所述数据库!这是我的代码:

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()

打印所有信息。我尝试了各种方法来到达我的桌子,products但我无法让它工作并不断收到AttributeError: 'Resource' object has no attribute 'execute'(或'list')异常。我试过这样的东西:

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

也可以查看我的表格,但它不起作用。我相信这是正确的方法,因为我可以连接,但我还没有弄清楚。有人知道答案吗?

标签: pythonpython-3.xgoogle-api-clientdiscovery

解决方案


根据文档,您应该能够使用以下代码访问您的表格。

请注意,您有一个 sql 项目,然后是项目上的一个实例,然后是实例中的一个数据库,然后您的表嵌套在该数据库中。

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)

我建议您查看 CLoud SQL for MySQL 的 REST API 参考资料,以便进一步阅读 ( https://cloud.google.com/sql/docs/mysql/admin-api/rest/v1beta4/databases/get )。


推荐阅读