我在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

最佳答案

确保您使用的数据库正确,并使用%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()


希望这可以帮助。

09-16 04:11