postgresql Psycog2不会返回任何数据

vyswwuz2  于 2023-11-18  发布在  PostgreSQL
关注(0)|答案(1)|浏览(164)

我正在学习使用PostgreSQL和Python。我正在使用Psycog 2库访问一个本地数据库,该数据库有一条记录:

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

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

字符串
我写了一个类Db_Interactor(是的,我知道这个名字很烂)来管理我所有的数据保存/访问。在示例化时,它创建了一个数据库连接(self.conn),在删除时关闭。连接不会抛出错误,也没有问题。问题是当我实际尝试获取一些数据时。我在Db_Interactor中有一个函数,它试图这样做,但它没有正确返回:

功能:

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

# NOTE: I got this config function from some tutorial I found

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

    # get section, default to postgresql
    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):
        """ Connect to the PostgreSQL database server """
        self.conn = None
        try:
            # read connection parameters
            self.params = config()

            # connect to the PostgreSQL server
            print('Connecting to the PostgreSQL database...')
            self.conn = psycopg2.connect(**self.params)

        # close the communication with the PostgreSQL
        except (Exception, psycopg2.DatabaseError) as error:
            print(error)

    def __del__(self):
        # close the communication with the PostgreSQL
        self.conn.close()
        print('Database connection closed.')
'''
    def execute(self,command):
        try:
            #TODO: figure out a squeal query to add a new record
            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())
    #tickers = ts.ticker_from_csv() 
    #stonks = ts.get_stocks_from_list(tickers)
#    for i in stonks:
#        db_int.add_record(i)

示例化和函数调用:

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.

尝试次数

我希望它返回我的数据,我不知道为什么。我试着切换字符串类型(从堆栈溢出的diff问题)并添加“;”,但没有改变。我通过运行psql(如上所示)和使用SELECT * FROM电子设备仔细检查数据库中是否有数据;数据确实显示。

vmjh9lq9

vmjh9lq91#

好的,我已经解决了。很明显是因为我使用psql命令将测试记录添加到了数据库中,当我试图使用python访问它时,它没有注册,而是只有示例化的空表。为什么会发生这种情况我仍然不知道。但对于我当前的项目来说,这已经足够了。工作正常。

相关问题