python - 无法使用 python 从 postgres 表中提取数据到 .ods 文件
问题描述
我正在尝试使用以下代码在 ods 文件中收集 postgres 查询的输出。我创建了一个read_table
成功读取 postgres 表的函数。
def read_table()
import psycopg2 as ps
import sys
con =None
try:
con=ps.connect("host, dbname, user,pwd....")
cur=con.cursor()
cur.execute("Select * from table_name")
rows=cur.fetchall()
for(row in rows):
print(row)
cur.close()
except (Exception, ps.DatabaseError) as error:
print(error)
finally:
if con is not None:
con.close()
from collections import OrderedDict
from pyexcel_ods import save_data
data=OrderedDict()
raw_data=read_table()
raw_data.update({'DATA':raw_data})
save_data("/home/myfile.ods", raw_data)
该表打印在 python shell 上,但未写入 .ods 文件。它给出以下错误:
raw_data.update({'DATA':raw_data})
AttributeError: 'NoneType' object has no attribute
如何在 ods 文件中保存和提取表格?所有软件包和模块都已安装,但我仍然收到此错误。
我是python的新手,所以请指导我。我在 Ubuntu 上使用 Postgres 数据库,使用 Idle3。
解决方案
您的方法 raw_data 不返回任何内容。您不想打印行,而是希望返回它们或产生它们,如下所示:return row
或yield row
代替print(row)
但是,可以使用 pandas 库在几行代码中完成您需要的操作:https ://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql_query.html https://pandas.pydata .org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html
推荐阅读
- windows - 修复 findstr 以忽略与路径匹配的文件名
- python-3.x - 根据条件更新特定的行数
- selenium - 使用 Zalenium(可扩展的硒网格)运行 dockerized Behat BDD 测试
- azure - Azure 函数 CosmosDb 绑定性能
- sql-server - 我在生成特定类型的数据时遇到问题
- sql - 比较 DB2 的 SQL 中的日期和时间
- powershell - 将 AD 信息移动到 excel 的脚本,有没有办法为描述值编写 if 函数?
- java - 读取图像时出现异常
- pdf - 使用 nltk 提取和标记单词 - 错误的输出
- unity3d - 构建完成,结果为“失败”UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)