I'm trying to collect output of a postgres query in ods-file using following code. I have created a function read_table
that reads the postgres table successfully.
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)
The table is printed on python shell but it is not written to .ods-file. It gives following error:
raw_data.update({'DATA':raw_data})
AttributeError: 'NoneType' object has no attribute
How do I save & extract the table in ods-file? All the packages & modules are installed, but still I get this error.
I'm a newbie in python, so please guide me. I'm using Postgres database on Ubuntu, using Idle3.
Your method raw_data does not return anything. Instead of printing the rows, you want to return them or yield them, like so: return row
or yield row
instead of print(row)
However, it is possible to do what you need in couple of lines of code with pandas library: 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