pysqlite: Placeholder substitution for column or table names?

主宰稳场 提交于 2019-11-27 04:38:50

You simply can not use placeholders for column or table names. I don't have a authoritative citation for this -- I "know" this only from having tried it and from failing. It makes some sense though:

  • If the columns and table could be parametrized, there would be little purpose to preparing (execute-ing) the SQL statement before fetching, since all parts of the statement could be replaced.
  • I'm not sure about pysqlite1, but MySQLdb automatically quotes all string parameters. Column and table names should not be quoted. So it would complicate the parsing required by the driver if it had to decide if a placeholder represented a column or table name versus a value that needs quoting.

In short, you've found the right way -- use string formating.

c.execute('SELECT {} FROM {} WHERE id=?'.format(column, table), row))

1 Not all drivers quote parameters -- oursql doesn't, since it sends SQL and arguments to the server separately.

chutz

As @unutbu answered, there is no way to use placeholders for table/column names. My suggestion to do what you are doing now, but to also quote the table names to protect yourself from a table or column that might have an odd name.

What does the SQL Standard say about usage of backtick(`)? already explains this to some extent, and in spite of the opinion in that answer, I would say that in your case, quoting is a good idea.

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