我在psql里面是可以正常获取的,Python就不行了
import psycopg2
a=psycopg2.connect(host='localhost',database='data',user='postgres',password=xxx',port=5432)
b=a.cursor()
b.execute('select * from users;')
for c in b.fetchall():print(c)
b.close()
C:\Users\Administrator\AppData\Local\Programs\Python\Python39-32\python.exe E:\Python3911\demo.py
进程已结束,退出代码0
缺少 psycopg2 模块
pip install psycopg2
代码感觉没啥毛病
检查一下代码中包含了从 psycopg2 导入的所有必需的模块和库,还有,是否确保在执行查询之前已经提交了连接,以确保已经在数据库中确实存在了所需的表和数据
可以将以下代码段添加到代码中,以确保在执行查询语句之前,数据库连接已经提交并可以正常连接
#connect to the database
a=psycopg2.connect(host='localhost',database='data',user='postgres',password='your_password',port=5432)
# create a cursor
b= a.cursor()
# commit any pending transaction to the database
a.commit()
# execute the query
b.execute('select * from users;')
# retrieve the results
results = b.fetchall()
# close the cursor
b.close()
# close the connection
a.close()
如果仍然无法正常工作,则可能需要考虑防火墙、IP 所在位置、端口权限等更全面的网络问题