How to prevent PyMySQL from escaping identifier names?

余生长醉 提交于 2019-12-24 03:42:33

问题


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).


回答1:


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.



来源:https://stackoverflow.com/questions/27618354/how-to-prevent-pymysql-from-escaping-identifier-names

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!