Python mysql.connector.errors。 %s使用引号传递给SQL查询

时间:2015-04-01 10:28:53

标签: python mysql

我在Python中执行以下代码

cursor.execute('SHOW DATABASES;')
ans_dblist = cursor.fetchall()


for db_name in ans_dblist:
  cursor.execute('SHOW TABLES FROM %s;', (db_name[0],))
  ans_tbl = cursor.fetchall()
  print ans_tbl

我收到了这个错误:

Traceback (most recent call last):
  File "./mysqlcon.py", line 12, in <module>
    cursor.execute('SHOW TABLES FROM %s;', (db_name[0],))
  File "/usr/lib/python2.6/site-packages/mysql/connector/cursor.py", line 507, in execute
    self._handle_result(self._connection.cmd_query(stmt))
  File "/usr/lib/python2.6/site-packages/mysql/connector/connection.py", line 722, in cmd_query
    result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
  File "/usr/lib/python2.6/site-packages/mysql/connector/connection.py", line 640, 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 ''information_schema'' at line 1

为什么%s被引号替换? SQL查询将找到基本&#39;信息架构而非信息架构(不含引号)。

3 个答案:

答案 0 :(得分:2)

MySQLPython在查询中对变量占位符使用标准字符串格式标记(“%”)这一事实可能会让事情变得混乱。

python的db-api中的查询占位符用于where子句以及insertupdate语句中使用的,并且正确地进行了santized /转义/引用db-api以避免SQL注入等。它们不应该用于表或字段名称。

所以,你想要的是使用字符串格式构建你的查询:

sql =  'SHOW TABLES FROM %s;' % (db_name[0],)
cursor.execute(sql)

由于db_name[0]来自受信任的来源,因此这里没有安全问题。

答案 1 :(得分:0)

我听说使用%格式化也不安全,或者这个错误?我尝试使用%格式,但“%s”记住以前查询的值,当我执行下一个查询时,我得到以下回复:

mysql.connector.errors.ProgrammingError: 1146 (42S02): Table 'test.CHARACTER_SETS' doesn't exist

“test.CHARACTER_SETS”不存在,我知道。 “test”是一个数据库,“CHARACTER_SETS”是一个表名。

我的完整代码很简单:

import mysql.connector
cnx = mysql.connector.connect(user='root', host='127.0.0.1', database='test')
cursor = cnx.cursor()

cursor.execute('SHOW DATABASES;')
ans_dblist = cursor.fetchall()


for db_name in ans_dblist:
  cursor.execute("SHOW TABLES FROM %s" % db_name[0])
  ans_tbl = cursor.fetchall()
  print ans_tbl

  for tbl_name in ans_tbl:
    cursor.execute("SHOW COLUMNS FROM %s where extra like 'auto_increment';" % tbl_name[0]) #There tbl_name[0]=CHARACTER_SETS, but %s=test.CHARACTER_SET. In above query %s=test, but why it passed to next query I don't know.

    column_autoincrement = cursor.fetchone()

此外,我尝试使用字典,%(db_name)s也在SQL查询中传入引号。

  cursor.execute("SHOW TABLES FROM %(db_name)s", {'db_name':db_name[0]})

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 ''information_schema'' at line 1

答案 2 :(得分:0)

我使用方法format

cursor.execute("SHOW TABLES FROM {0}".format(db_name[0]))

它有效! :)