简体   繁体   English

字符串中插入单引号的python变量

[英]python variable in string inserting single quote

I have the following bit of python code: 我有以下python代码:

insert_table = settings.INSERT_TABLE_NAME

        self.execute(
            """
            INSERT INTO `%(insert_table)s`
            (time, rem_host, username, our_result,
              upstream_result, reason, solution, difficulty)
            VALUES
            (FROM_UNIXTIME(%(time)s), %(host)s,
              %(uname)s,
              %(lres)s, 'N', %(reason)s, %(solution)s, %(difficulty)s)
            """,
            {
                "insert_table": insert_table,
                "time": v[4],
                "host": v[6],
                "uname": v[0],
                "lres": v[5],
                "reason": v[9],
                "solution": v[2],
                "difficulty": v[3]
            }
        )

The problem I'm having is that the result of the SQL query contains single quotes around the 'insert_table' variable so the result is: 我遇到的问题是SQL查询的结果在'insert_table'变量周围包含单引号,因此结果是:

INSERT INTO `'my_table_name'`

so it's obviously breaking the query. 因此很明显会破坏查询。

Anyone have any suggestion on how to correctly configure this? 有人对如何正确配置此有任何建议吗?

You cannot use SQL parameters to interpolate table names. 您不能使用SQL参数来插值表名称。 You'll have to use classic string formatting for those parts. 您必须为这些部分使用经典的字符串格式。

That's the point of SQL parameters; 这就是SQL参数的 ; they quote values so they cannot possibly be interpreted as SQL statements or object names. 它们引用值,因此它们不可能解释为SQL语句或对象名称。

The following works, but you need to be careful where your table names come from: 可以使用以下方法,但是您需要注意表名的来源:

"""
INSERT INTO `{}`
(time, rem_host, username, our_result,
  upstream_result, reason, solution, difficulty)
VALUES
(FROM_UNIXTIME(%(time)s), %(host)s,
  %(uname)s,
  %(lres)s, 'N', %(reason)s, %(solution)s, %(difficulty)s)
""".format(insert_table),
{
    "time": v[4],
    "host": v[6],
    "uname": v[0],
    "lres": v[5],
    "reason": v[9],
    "solution": v[2],
    "difficulty": v[3]
}

If insert_table is user-sourced, your best bet is to first vet it against a pre-determined list of existing tablenames. 如果insert_table是用户来源的,最好的选择是首先对现有表名的预定列表进行审核。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM