首页 > 解决方案 > 用 python 连接 postgresql 中的 sqlalchemy - google coolab

问题描述

我想通过 google colab 连接到 postgres 数据库服务器,但是当我使用此代码连接时,出现以下错误。请我需要帮助

from sqlalchemy import create_engine
import psycopg2

host= "xxx.xxx.x.xxx:5432"
user= "user"
password= "psw"
nombre_db= "name"
url= "postgresql://{user}:{password}@{host}/{nombre_db}"

engine =create_engine(url)
conn = engine.connect()
conn

错误:

OperationalError                          Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/sqlalchemy/engine/base.py in _wrap_pool_connect(self, fn, connection)
   3210         try:
-> 3211             return fn()
   3212         except dialect.dbapi.Error as e:

39 frames
OperationalError: could not translate host name "{host}" to address: Name or service not known

The above exception was the direct cause of the following exception:

OperationalError                          Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/psycopg2/__init__.py in connect(dsn, connection_factory, cursor_factory, **kwargs)
    128 
    129     dsn = _ext.make_dsn(dsn, **kwargs)
--> 130     conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
    131     if cursor_factory is not None:
    132         conn.cursor_factory = cursor_factory

OperationalError: (psycopg2.OperationalError) could not translate host name "{host}" to address: Name or service not known

(Background on this error at: http://sqlalche.me/e/14/e3q8)

标签: pythonpostgresqlgoogle-colaboratory

解决方案


我不知道我是否应该把它写成答案。

您忘记f了创建f-string类似的前缀f"..."

url = f"postgresql://{user}:{password}@{host}/{nombre_db}"

如果您使用print()调试代码,那么您会看到差异

# without `f`

url = "postgresql://{user}:{password}@{host}/{nombre_db}"
print(url)

# with `f`

url = f"postgresql://{user}:{password}@{host}/{nombre_db}"
print(url)

结果:

# without `f`

postgresql://{user}:{password}@{host}/{nombre_db}

# with `f`

postgresql://user:psw@xxx.xxx.x.xxx:5432/name

推荐阅读