python - Python脚本,从本地机器查询GCP postgresql db?
问题描述
我有一个 GCP 工作区,配有一个 Postgresql 数据库。我经常需要从数据库中插入和/或选择行。我一直在寻找一个 python 脚本,它将 (A) 连接到 GCP,然后 (B) 连接到数据库,然后 (C) 查询特定的表。如果可能的话,我不希望对我的凭据进行硬编码,这样我就可以与团队中的其他人共享这个脚本,并且只要他们是授权用户,它就可以毫无问题地运行。
有人有这样的剧本吗?
解决方案
我相信我刚刚在这里回答了您的问题:Access GCP Cloud SQL from AI notebook?
使用另一篇文章中提到的Cloud SQL Python 连接器,您可以运行如下所示的脚本来连接到您的数据库并运行查询:
# Copyright 2021 Google LLC.
# SPDX-License-Identifier: Apache-2.0
import os
from google.cloud.sql.connector import connector
# Connect to the database
conn = connector.connect(
os.getenv("INSTANCE_CONNECTION_NAME"),
"pg8000",
user=os.getenv("DB_USER"),
password=os.getenv("DB_PASSWORD"),
db=os.getenv("DB_NAME")
)
# Execute a query
cursor = conn.cursor()
cursor.execute("SELECT * from my_table")
# Fetch the results
result = cursor.fetchall()
# Do something with the results
for row in result:
print(row)
实例连接名称应采用project:region:instance
. 如果您不想对数据库凭据进行硬编码,则可以改为从环境变量中读取它们。
推荐阅读
- flutter - 如何在小部件之外获取 TextFiled 值
- c# - 旋转立方体并跟踪它的侧面
- python - 网页源不显示脚本内容
- django - 在尝试使用带有 Amazon -SQS 的 ElasticBeantalk 上的 celery 和 django 并运行时,我得到 [Errno 13] Permission denied?
- swift - 使用 RevenueCat 包装“purchaserInfo”以便在整个代码中轻松比较的最佳方法是什么
- python - 一种使用 python MySQLdb 连接器禁用 SSL 的方法
- neo4j - Neo4j 递归函数
- spring-data-redis - 如何使用 spring.cache.redis.key-prefix 为 cacheNames 加上前缀?
- css - 如何仅在某些条件下添加样式?
- javascript - 转换为字符串的数组