如何使psycopg2发出嵌套的引号? [英] How to make psycopg2 emit nested quotes?

查看:113
本文介绍了如何使psycopg2发出嵌套的引号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按照>不存在关系在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆