PyMySQL - 使用字符串作为 cursor.execute 参数

PyMySQL - Using a string as cursor.execute argument

我的问题是在cursor.execute下面传递一个字符串

import pymsyql
import json

connection = pymysql.connect(
        host='localhost', user='u_u_u_u_u',
        password='passwd', db='test',
        charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor
)

def get_data(table):
    try:
        with connection.cursor() as cursor:
            sql = """
                SELECT * FROM %s;
            """
            cursor.execute(sql, (table,))
            result = cursor.fetchall()
            return json.dumps([dict(ix) for ix in result])

    except (TypeError, pymysql.err.ProgrammingError) as error:
        print(error)
    finally:
        pass

get_data('table_1')

connection.close()

我收到错误

pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''table_1'' at line 1")

似乎 execute 不希望将字符串作为参数传递;当我直接输入字符串时,如 cursor.execute(sql, ('table_1',)),我得到同样的错误。

我对导致问题的原因感到困惑,双引号 ''table_1'' 令人困惑。谁能告诉我这是怎么回事?

您不能将 table 名称作为参数传递,唉。您必须将其合并到查询字符串中:

        sql = """
            SELECT * FROM `{0}`;
        """.format(table)
        cursor.execute(sql)