首页 > 解决方案 > python中的Postgres数据库连接

问题描述

如何访问 python 中 linux 服务器机器上的 postgre 数据库?我已经使用 putty 终端访问了它,但我需要通过 python 访问数据库中的表,但我无法做到这一点。

标签: pythonpostgresqlputty

解决方案


#!/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 访问权限,并且您不需要以这种方式搞乱数据库配置。此外,您可能不允许更改配置。


推荐阅读