为什么python mysql连接器会在execute()中将fromtrophes插入from子句?

时间:2017-11-09 00:50:33

标签: python mysql mysql-connector

我试图使用Python和mysql-connector将变量插入到sql select query< s; from子句中。但是,看来execute()是在变量名称周围添加撇号。为什么会发生这种情况,我该怎么做才能阻止它呢?

我在where子句中插入变量没有问题。

我的代码:

import mysql.connector
import sys

password = sys.argv[1]
conn = mysql.connector.connect(user='root', password=password, database='arch')
cursor = conn.cursor()

tables = ['A', 'B', 'C']
for table in tables:
    query = 'SELECT * FROM %s'
    cursor.execute(query, [table])
    results = cursor.fetchall()
    print(results)

导致追溯:

Traceback (most recent call last):
  File "smoke.py", line 11, in <module>
    cursor.execute(query, [table])
  File "/usr/local/lib/python3.4/dist-packages/mysql/connector/cursor.py", line 515, in execute
    self._handle_result(self._connection.cmd_query(stmt))
  File "/usr/local/lib/python3.4/dist-packages/mysql/connector/connection.py", line 488, in cmd_query
    result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
  File "/usr/local/lib/python3.4/dist-packages/mysql/connector/connection.py", line 395, in _handle_result
    raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1064 (42000): 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 ''A'' at line 1

请注意回溯中表名两侧的两个单引号。

当我做&#34; SELECT * FROM A&#34;直接进入mysql解释器,运行该查询没有问题。

0 个答案:

没有答案