PyMySQL在Python中为表名指定一个变量

时间:2017-02-16 04:30:02

标签: python mysql pymysql

我在Python 2.7中使用PyMySQL。我必须创建一个函数 - 在给定表名的情况下,查询将查找所有列名的唯一值。

由于涉及多个表,我不想硬编码表名。现在,更简单的查询就像:

cursor.execute("  SELECT DISTINCT(`Trend`) AS `Trend` FROM `Table_1`  ORDER BY `Trend` DESC      ")

我想做类似的事情:

tab = 'Table_1'
cursor.execute("  SELECT DISTINCT(`Trend`) AS `Trend` FROM tab ORDER BY `Trend` DESC      ")

我收到以下错误:

ProgrammingError: (1146, u"Table 'Table_1.tab' doesn't exist")

有人可以帮忙。 TIA

1 个答案:

答案 0 :(得分:0)

确保您正在使用的数据库是正确的,并使用%s格式化您的sql语句。

DB_SCHEMA='test_db'
table_name='table1'
connection = pymysql.connect(host=DB_SERVER_IP,
                             port=3306,
                             db=DB_SCHEMA,
                             charset='UTF8',
                             cursorclass=pymysql.cursors.DictCursor
                             )
try:
    with connection.cursor() as cursor:
        sql = "SELECT DISTINCT(`Trend`) AS `Trend` FROM `%s` ORDER BY `Trend` DESC"%(table_name)

        cursor.execute(sql)

    connection.commit()
except Exception as e:
    print e
finally:
    connection.close()

希望这有帮助。

相关问题