python - python中的Postgres数据库连接
问题描述
如何访问 python 中 linux 服务器机器上的 postgre 数据库?我已经使用 putty 终端访问了它,但我需要通过 python 访问数据库中的表,但我无法做到这一点。
解决方案
#!/usr/bin/env python3
import sys
import psycopg2
try:
conn = psycopg2.connect("dbname='dbname' user='dbuser' host='localhost' port='5432' password='dbpass'")
except psycopg2.DatabaseError:
sys.exit('Failed to connect to database')
try:
cursor = conn.cursor()
cursor.execute("SELECT * FROM test_table WHERE id < 10000")
dbRecord = cursor.fetchone()
if dbRecord == None:
print('ERROR: First record not found', file=sys.stderr)
else:
print('Loaded {}'.format(dbRecord))
dbRecordId = dbRecord[0]
conn.commit()
cursor.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
此外,您可能需要允许在 postgres 中访问。要允许用户使用登录名/密码对连接到服务器,请取消注释或添加以下行pg_hba.conf
(通常位于/etc/postgresql/{postgres_version}/main/pg_hba.conf
):
# "local" is for Unix domain socket connections only
local all all peer
# IPv4 local connections:
host all all 127.0.0.1/32 md5
# IPv6 local connections:
host all all ::1/128 md5
编辑:哦,我刚刚意识到你的 postgres 服务器在远程机器上。以下选项可能适用:
- 将您的 IP 添加到上面的配置中并在脚本中
pg_hba.conf
更改host='localhost'
为。host='your.server.address.or.ip'
或者: - 使用ssh 端口转发可以在本地机器上访问远程服务器的 5432 端口。在这种情况下,请
localhost
按原样保留脚本。
后者可能是最干净和最快的选择,因为您似乎已经拥有 ssh 访问权限,并且您不需要以这种方式搞乱数据库配置。此外,您可能不允许更改配置。
推荐阅读
- jmeter - 在 JMeter 命令行之后执行的其他命令失败
- ios - 在 Mac Catalyst 上关闭“.sheet”的手势
- java - 更改系统外观主题
- android - 当我使用 ./gradlew lintDebug 构建应用程序时,无法从 mavenCentral 获取 firebase-ui-auth
- sql-server - SQL Server 2016 上的内置策略错误
- sql - 请求优化
- html - SCSS - 悬停效果扩展到其他元素
- javascript - 当 jwt 刷新令牌未过期时,React Native 应用程序注销
- javascript - Service Worker 无法在新的 chrome 窗口中启动
- spring-boot - 服务在一段时间后自动从领事注销