cursor.query( 'select * from %s;', ('thistable',) ) throws syntax error 1064: …near ' 'thistable' ' at

主宰稳场 提交于 2021-01-28 06:28:18

问题


MySQLdb: cursor.query( 'select * from %s;', ('thistable',) )

should end up as: 'select * from thistable'

actually ends up as: "select * from 'thistable' "

the db natually throws syntax error: ...near ' 'thistable' ' at ...

It behaves as though the data converter is including the string's quotes as part of the string, ie the string is " 'thistable' " instead of 'thistable'. Any and all help with this is deeply appreciated. One thing I did notice in my questing is that the script's charset is utf8, while the db server and db are latin1. Could this be my problem?

OS: os X Sierra

python: 3.6

MySQL: 5.3.6

mysql-connector-c: 6.1.11


回答1:


There's a difference between building dynamic SQL and building parameterized queries.

In general, parameterized queries let you plug in values for comparison/input, but not database objects. So, your application code assumes that %s is a quoted literal, not an database object.

If you need to dynamically add in database objects (tables, columns, procedure names, etc.), you will probably need to build the query string first, with placeholders (like %s) for actual parameters you need to pass in.

In this case, ypercubeᵀᴹ's suggestion to simply use the string 'select * from thistable' directly. If you needed to run the same query against multiple tables, loop through the list of table, building the string like:

queryString = 'SELECT * FROM ' + currTable


来源:https://stackoverflow.com/questions/46717146/cursor-query-select-from-s-thistable-throws-syntax-error-1064

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