如何在选择查询python中使用传递的参数作为表名? [英] How to use passed parameter as table Name in Select query python?

查看:258
本文介绍了如何在选择查询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中使用传递的参数作为表名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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