Search code examples
pythonmysqlstring-formattingpymysqlpython-db-api

How to prevent PyMySQL from escaping identifier names?


I am utilizing PyMySQL with Python 2.7 and try to execute the following statement:

'INSERT INTO %s (%s, %s) VALUES (%s, %s) ON DUPLICATE KEY UPDATE %s = %s'

With the following parameters:

('artikel', 'REC_ID', 'odoo_created', u'48094', '2014-12-23 10:00:00', 'odoo_modified', '2014-12-23 10:00:00')

Always resulting in:

{ProgrammingError}(1064, u"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 ''artikel' ('REC_ID', 'odoo_created')\n
VALUES ('48094', '2014-12-' at line 1")

Which seems to me like PyMySQL is escaping all strings during formatting. How can I prevent that for database identifiers like table and column names? It corrupts the statement, since SELECTs from string literals (SELECT * FROM "table") are not possible in comparison to tables (SELECT * FROM table).


Solution

  • That's the point of DB API's substitution. It escapes values. You really shouldn't need to escape table/column names.

    I'd use something like:

    execute('''INSERT INTO {} ({}, {}) VALUES (%s, %s) ON DUPLICATE KEY UPDATE {} = %s'''
        .format('artikel', 'REC_ID', 'odoo_created', 'odoo_modified'),
        (u'48094', '2014-12-23 10:00:00', '2014-12-23 10:00:00')
    )
    

    Or, you know, just write the names directly.