使用Python连接CloudSQL Postgres Db

问题描述 投票:0回答:1

我是 DevOps 工程师,请原谅我缺乏 Python 开发知识。我正在尝试使用 Python 连接 CloudSQL Postgres 14 Db。这样我就可以插入数据并从我的应用程序中读取数据。有人可以帮助我理解为什么当我尝试运行 python 脚本时出现错误吗?

使用的参考:用于连接CloudSQL和python的Stackoverflow参考

# 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("angelic-hexagon-307814:us-central1:sqlpg1234"),
    "pg8000",
    user=os.getenv("test1"),
    password=os.getenv("test1"),
    db=os.getenv("postgres")
)

# Execute a query
cursor = conn.cursor()
cursor.execute("SELECT * from accounts")

# Fetch the results
result = cursor.fetchall()

# Do something with the results
for row in result:
    print(row)

我有一个文件名为 sql.py 的文件,我运行命令

python3 sql.py
来运行 python 脚本。但我遇到了以下错误,但无法调试其背后的原因。有人可以帮忙吗?

sidharth@Sidharths-Air python % python3 sql.py
Traceback (most recent call last):
  File "/Users/sidharth/python/sql.py", line 8, in <module>
    conn = connector.connect(
AttributeError: module 'google.cloud.sql.connector.connector' has no attribute 'connect'. Did you mean: 'Connector'?
python postgresql google-cloud-platform google-cloud-sql
1个回答
0
投票

要连接到 Cloud SQL 数据库,您可以使用 pg8000 库和 sqlalchemy 库

安装pg8000

pip install sqlalchemy pg8000

这是连接示例

import os
from sqlalchemy import create_engine

db_user = os.getenv("test")
db_pass = os.getenv("test")
db_name = os.getenv("postgres")
cloud_sql_connection_name = os.getenv("angelic-hexagon-307814:us-central1:test-db")

connection_name = f"/cloudsql/{cloud_sql_connection_name}"

db = create_engine(
    f"postgresql+pg8000://{db_user}:{db_pass}@{connection_name}/{db_name}"
)

with db.connect() as conn:
    result = conn.execute("SELECT * from accounts")
    for row in result:
        print(row)
© www.soinside.com 2019 - 2024. All rights reserved.