Rabbie
Rabbie

Reputation: 1771

python variable in string inserting single quote

I have the following bit of python code:

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:

INSERT INTO `'my_table_name'`

so it's obviously breaking the query.

Anyone have any suggestion on how to correctly configure this?

Upvotes: 0

Views: 728

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121306

You cannot use SQL parameters to interpolate table names. You'll have to use classic string formatting for those parts.

That's the point of SQL parameters; they quote values so they cannot possibly be interpreted as SQL statements or object names.

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.

Upvotes: 1

Related Questions