通过Python连接谷歌云MySQL;如何访问表?

问题描述

遵循 this tutorial 后,我可以运行一个脚本来打印我的数据库的所有详细信息。但是,我不知道如何对所述数据库执行某些操作!这是我的代码

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

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

解决方法

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

请注意,您有一个 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)。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...