【问题标题】:Python script, query to GCP postgresql db from local machine?Python脚本,从本地机器查询GCP postgresql db?
【发布时间】:2021-05-05 17:48:52
【问题描述】:

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

有人有这样的脚本吗?

【问题讨论】:

    标签: python postgresql google-cloud-platform


    【解决方案1】:

    我相信我刚刚在这里回答了你的问题:Access GCP Cloud SQL from AI notebook?

    使用在另一篇文章中提到的Cloud SQL Python Connector,您可以运行如下所示的脚本来连接到您的数据库并运行查询:

    # 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。如果您不想对数据库凭据进行硬编码,则可以改为从环境变量中读取它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-12
      • 1970-01-01
      • 2020-08-23
      • 2017-11-01
      • 1970-01-01
      • 2021-04-16
      • 1970-01-01
      相关资源
      最近更新 更多