首页 > 解决方案 > 如何从 psycopg2 请求表大小?

问题描述

实验上,以下工作:

from psycopg2 import sql
def table_size(conn, table):
    with conn.cursor() as cu:
        cu.execute(sql.SQL("SELECT pg_table_size({t}), pg_indexes_size({t});").format(t=sql.Literal(table)))
        return cu.fetchall()[0]

但是,我想知道我是否正确使用sql.SQL/ 。sql.Literal

例如,如何将表名和列名与值结合起来?

def get(conn,table,key,value,column):
    with conn.cursor() as cu:
        cu.execute(sql.SQL("SELECT {c} FROM {t} WHERE {k} = %s;").format(
            c=sql.Identifier(column),t=sql.Identifier(table),k=sql.Identifier(key)),
                   (value, ))
        return cu.fetchall()

标签: pythonpython-3.xpsycopg2

解决方案


推荐阅读