【发布时间】:2021-02-18 18:30:25
【问题描述】:
我有一个 python 应用程序,我正在尝试访问 Google 云服务上的 MySQL 数据库。
我一直关注set up guide 通过外部应用程序 (Python) 进行连接,我正在使用 pymysql 包。我正在尝试通过代理进行连接,并且已经通过 gcloud auth 从控制台登录验证了我的连接。
到目前为止,我可以通过控制台访问数据库,但我需要能够从我的 python 脚本中进行查询来构建它。当我尝试按原样运行它时,我收到以下错误: OperationalError: (2003, "Can't connect to MySQL server on '34.86.47.192' (timed out)")
这是我正在使用的功能,其中安全敏感信息已加星标:
def uploadData():
# cd to the directory with the MySQL exe
os.chdir('C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin')
# Invoke the proxy
subprocess.call('start cloud_sql_proxy_x64.exe -instances=trans-cosine-289719:us-east4:compuweather', shell=True)
# Create connection
# I have also tried host = '127.0.0.1' for localhost here
conn = pymysql.connect(host='34.86.47.192',
user='root',
password='*******',
db='gribdata')
try:
c = conn.cursor()
# Use the right databse
db_query = 'use gribdata'
c.execute(db_query)
query = 'SELECT * FROM clients'
c.execute(query)
result = c.fetchall()
print(result)
except Error as e:
print(e)
finally:
conn.close()
【问题讨论】:
-
您是如何获得 GCP 授权的?您是否设置了具有适当权限的服务帐号来运行代理并连接到 Cloud SQL?
-
顺便说一句,最简单的方法是使用
-credential_file参数将其传递给 cloud_sql_proxy(它采用服务帐户 json 文件的路径)。该服务帐号需要具有 Cloud SQL Client 角色才能与 Cloud SQL 实例通信。
标签: python mysql gcloud pymysql