简体   繁体   中英

How to get PostgreSQL database size from Python?

I am using psycopg2 to get a PostgreSQL database size in Python3.

dbname = 'my_pg_database'
q = 'select pg_total_relation_size(%s);'
conn.cursor.execute(q, (dbname, ))
row = conn.cursor.fetchone()
print(str(row[0]))

I have also tried with the same code but switching second line:

q = 'select pg_total_relation_size((%s));'

And changing second and third lines:

dbname = 'my_pg_database'
q = 'select pg_total_relation_size({dbname});'.format(dbname=dbname)
conn.cursor.execute(q)
row = conn.cursor.fetchone()
print(str(row[0]))

I always get the same syntax error, I had a lot this problem before with other queries, but I managed to deal with this using format or the other way, but not in this case. Anyone knows why?

EDIT

The errors I am getting are:

With the first code:

psycopg2.ProgrammingError: relation "my_pg_database" does not exist LINE 1: select pg_total_relation_size('my_pg_database');

By the way, here there is a kind of arrow pointing to the first quote of the second line.

With the third code:

psycopg2.ProgrammingError: column "my_pg_database" does not exist LINE 1: select pg_total_relation_size(my_pg_database);

And here there is a kind of arrow pointing to the m of my_pg_database of the second line.

Note that the first error is talking about relation and the second one about column.

You're using the wrong function, you need pg_database_size() to get the size of your database. pg_total_relation_size() is for a single table and it's indexes.

Check the manual for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM