使用 SQLAlchemy 时创建 TCP 连接

演示如何使用 SQLAlchemy 创建与 Cloud SQL for SQL Server 的 TCP 连接。

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

Python

# Remember - storing secrets in plaintext is potentially unsafe. Consider using
# something like https://cloud.google.com/secret-manager/docs/overview to help keep
# secrets secret.
db_user = os.environ["DB_USER"]
db_pass = os.environ["DB_PASS"]
db_name = os.environ["DB_NAME"]
db_host = os.environ["DB_HOST"]

# Extract host and port from environment variable DB_HOST
host_args = db_host.split(":")
db_hostname, db_port = host_args[0], int(host_args[1])

# SQL Server drivers don't account for this
if db_hostname == "localhost":
    db_hostname = "127.0.0.1"

# The SQLAlchemy engine will help manage interactions, including automatically
# managing a pool of connections to your database
pool = sqlalchemy.create_engine(
    # Equivalent URL:
    # mssql+pytds://<db_user>:<db_pass>@/<host>:<port>/<db_name>?driver=ODBC+Driver+17+for+SQL+Server
    sqlalchemy.engine.url.URL.create(
        "mssql+pytds",
        username=db_user,
        password=db_pass,
        database=db_name,
        host=db_hostname,
        port=db_port,
    ),
    **db_config
)

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器