You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Psycopg2查询PostgreSQL无数据返回问题求助

Psycopg2查询PostgreSQL返回空列表排查

我用Python结合Psycopg2库连接本地PostgreSQL数据库,psql命令行能正常查询到electronics表的记录:

[postgres@<my-ip> ~]$ /usr/local/pgsql/bin/psql
psql (16.0)
Type "help" for help.

postgres=# SELECT * FROM electronics;
      <timestamp>    |    <text>   | <number> 
---------------------+-------------+-------
 1999-01-08 04:05:06 | your_mother |    69
(1 row)

但自己编写的Db_Interactor类,实例化时连接无错误,调用select_all方法查询却返回空列表。相关代码及运行输出如下:

代码实现

#!/usr/bin/python
from configparser import ConfigParser
import psycopg2

def config(filename='database.ini', section='postgresql'):
    parser = ConfigParser()
    parser.read(filename)

    db = {}
    if parser.has_section(section):
        params = parser.items(section)
        for param in params:
            db[param[0]] = param[1]
    else:
        raise Exception('Section {0} not found in the {1} file'.format(section, filename))

    return db

class Db_Interactor:

    def __init__(self):
        self.conn = None
        try:
            self.params = config()
            print('Connecting to the PostgreSQL database...')
            self.conn = psycopg2.connect(**self.params)
        except (Exception, psycopg2.DatabaseError) as error:
            print(error)

    def __del__(self):
        self.conn.close()
        print('Database connection closed.')

'''
    def execute(self,command):
        try:
            cur = self.conn.cursor()
            cur.excecute(command)
            out = cur.fetchall()
            cur.close()
            if out is None:
                return 'Nothing to Return'
            return out
        except (Exception, psycopg2.DatabaseError) as error:
            print(error)
            return None

    def add_record(self,dta_dict):
        try:
            cur = self.conn.cursor()
            cur.execute('')
            cur.close()
        except (Exception, psycopg2.DatabaseError) as error:
            print(error)
'''
    def select_all(self, table = None):
        if table is None:
            table = """electronics"""
        out = None
        try:
            cur = self.conn.cursor()
            print('cursor created')
            cur.execute("""SELECT * FROM """+table+""";""")
            print('query excecute')
            out = cur.fetchall()
            print('output read:')
            print(out)
            cur.close()
            print('cursor closed')
        except (Exception, psycopg2.DatabaseError) as error:
            print(error)
        return out


if __name__ == "__main__":
    db_int = Db_Interactor()
    print(db_int.select_all())

运行输出

Connecting to the PostgreSQL database... 
cursor created
query excecuted
output read:
[]
cursor closed
[]
Database connection closed. 

已尝试调整字符串格式、添加分号等,问题仍未解决,请求排查原因。


排查方向及解决方案

  1. 确认连接的数据库是否正确
    psql默认连接的是postgres数据库,检查database.ini中的database参数,确保与psql连接的是同一个库。如果代码连接的是其他数据库,自然查不到electronics表的数据。

  2. 指定表的schema
    PostgreSQL默认使用public schema,若代码连接的用户默认schema不是public,需要在查询语句中明确指定:

    cur.execute("""SELECT * FROM public.electronics;""")
    
  3. 检查事务自动提交设置
    Psycopg2默认不会自动提交事务,虽然查询操作通常不受事务状态影响,但可尝试在连接后开启自动提交,避免潜在的事务隔离问题:

    def __init__(self):
        self.conn = None
        try:
            self.params = config()
            print('Connecting to the PostgreSQL database...')
            self.conn = psycopg2.connect(**self.params)
            self.conn.autocommit = True  # 添加这一行
        except (Exception, psycopg2.DatabaseError) as error:
            print(error)
    
  4. 检查表名大小写与权限

    • PostgreSQL默认将未加引号的表名转为小写,确认代码中的表名与实际表名一致(避免创建表时使用了带引号的大小写混合名称)。
    • 确认连接数据库的用户拥有electronics表的SELECT权限,可通过psql执行GRANT SELECT ON electronics TO <your-user>;赋予权限。
  5. 修正代码缩进问题
    原代码中select_all方法的缩进有误(与类的其他方法级别不一致),虽然运行输出显示代码执行了,但需确保方法缩进正确,避免潜在的语法或作用域问题。

内容的提问来源于stack exchange,提问作者JackCooperUsesVim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 11:54:52