python - 用 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)
解决方案
我不知道我是否应该把它写成答案。
您忘记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
推荐阅读
- python - Python:检查是否可以从另一组创建一组
- syntax - 连接的verilog位选择
- javascript - 为什么 querySelector('div span') 匹配,即使 querySelector('div') 不匹配?
- javascript - VS Code 编辑器击穿 .click() 函数文本 #jQuery
- node.js - 如何仅使用 multerS3 将文件类型限制为图像?
- python - 在 Python 中没有错误的中断循环 - Selenium
- reactjs - 使用反应钩子在上下文提供者中添加多个状态
- haskell - 如何防止某些值(或状态)在线程之间共享?
- yarnpkg - 如何创建一个底层链?
- python - Python 类和 __init___ 构造函数,如何创建一个列表变量?