如何在选择查询python中使用传递的参数作为表名?

编程入门 行业动态 更新时间:2024-10-27 04:34:36
本文介绍了如何在选择查询python中使用传递的参数作为表名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下从表中提取数据的函数,但我想将函数中的表名作为参数传递...

i have the following function which extracts data from table, but i want to pass the table name in function as parameter...

def extract_data(table): try: tableName = table conn_string = "host='localhost' dbname='Aspentiment' user='postgres' password='pwd'" conn=psycopg2.connect(conn_string) cursor = conn.cursor() cursor.execute("SELECT aspects_name, sentiments FROM ('%s') " %(tableName)) rows = cursor.fetchall() return rows finally: if conn: conn.close()

当我将函数调用为extract_data(Harpar)时:Harpar是表名,但是它给出了一个错误,即未定义'Harpar'。 hepl?

when i call function as extract_data(Harpar) : Harpar is table name but it give an error that 'Harpar' is not defined.. any hepl ?

推荐答案

更新:自psycopg2 2.7版起:

您现在可以使用psycopg2的sql模块编写这种类型的动态查询:

You can now use the sql module of psycopg2 to compose dynamic queries of this type:

from psycopg2 import sql query = sql.SQL("SELECT aspects_name, sentiments FROM {}").format(sql.Identifier(tableName)) cursor.execute(query)

Pre< 2.7 :

按以下方式使用AsIs适配器:

Use the AsIs adapter along these lines:

from psycopg2.extensions import AsIs cursor.execute("SELECT aspects_name, sentiments FROM %s;",(AsIs(tableName),))

如果没有AsIs适配器,psycopg2将转义查询中的表名。

Without the AsIs adapter, psycopg2 will escape the table name in your query.

更多推荐

如何在选择查询python中使用传递的参数作为表名?

本文发布于:2023-10-27 02:45:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1532073.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   如何在   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!