首页 > 解决方案 > Python脚本,从本地机器查询GCP postgresql db?

问题描述

我有一个 GCP 工作区,配有一个 Postgresql 数据库。我经常需要从数据库中插入和/或选择行。我一直在寻找一个 python 脚本,它将 (A) 连接到 GCP,然后 (B) 连接到数据库,然后 (C) 查询特定的表。如果可能的话,我不希望对我的凭据进行硬编码,这样我就可以与团队中的其他人共享这个脚本,并且只要他们是授权用户,它就可以毫无问题地运行。

有人有这样的剧本吗?

标签: pythonpostgresqlgoogle-cloud-platform

解决方案


我相信我刚刚在这里回答了您的问题: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. 如果您不想对数据库凭据进行硬编码,则可以改为从环境变量中读取它们。


推荐阅读