如何使psycopg2发出嵌套的引号? [英] How to make psycopg2 emit nested quotes?
问题描述
按照>不存在关系在pg_table_size 中,我需要发出嵌套的单引号和:
As per "relation does not exist" in pg_table_size, I need to emit nested single and double quotes:
import psycopg2 as pg
from psycopg2 import sql
conn = pg.connect("dbname=test user=test")
table_name = "testDB"
cu = conn.cursor()
cu.execute(sql.SQL("SELECT pg_table_size(%s)"), (table_name,))
发出 SELECT pg_table_size('testDB')
会引发
psycopg2.ProgrammingError:关系 testdb不存在
psycopg2.ProgrammingError: relation "testdb" does not exist
而
cu.execute(sql.SQL("SELECT pg_table_size({t})").format(t=sql.Identifier(table_name)))
发出 SELECT pg_table_size( testDB)
psycopg2.ProgrammingError:列 testDB不存在
psycopg2.ProgrammingError: column "testDB" does not exist
很显然,
cu.execute(sql.SQL("SELECT pg_table_size(%s)"),('"testDB"',))
工作正常,但我想找到官方方式发出 SELECT pg_table_size(' testDB')
。
works fine, but I want to find the "official" way to emit SELECT pg_table_size('"testDB"')
.
实验上,以下工作原理:
Experimentally, the following works:
cu.execute(sql.SQL("SELECT pg_table_size(%s)"),
(sql.Identifier(table_name).as_string(conn), ))
这是TRT吗?
推荐答案
您可以使用Postgres函数 quote_ident(字符串文本):
You can use the Postgres function quote_ident(string text):
cu.execute("SELECT pg_table_size(quote_ident(%s))", (table_name, ))
我认为您的最后一个示例是上述解决方案的不错选择。
I think your last example is a good alternative for the above solution.
这篇关于如何使psycopg2发出嵌套的引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!