Python使用mysql连接器列表数据库LIKE然后按顺序使用这些数据库并运行查询

时间:2015-01-02 18:29:38

标签: python mysql database

我尝试使用pythong和mysql-connector库编写脚本。脚本应该连接到mysql服务器做一个" SHOW DATABASES LIKE< pdns _%'然后使用查询返回的结果使用每个数据库,然后在使用该数据库时运行另一个查询。

这是代码

import datetime
import mysql.connector
from mysql.connector import errorcode


cnx = mysql.connector.connect (user='user', password='thepassword',
                               host='mysql.server.com',buffered=True)
cursor = cnx.cursor()

query = ("show databases like 'pdns_%'")

cursor.execute(query)

databases = query

for (databases) in cursor:
    cursor.execute("USE %s",(databases[0],))
    hitcounts = ("SELECT Monthname(hitdatetime) AS 'Month', Count(hitdatetime) AS 'Hits' WHERE  hitdatetime >= Date_add(Last_day(Date_sub(Curdate(), interval 4 month)), interval 1 day) AND hitdatetime < Date_add(Last_day(Date_sub(Curdate(), interval 1 month)), interval 1 day) GROUP  BY Monthname(hitdatetime) ORDER BY Month(hitdatetime)")
    cursor.execute(hitcounts)
    print(hitcounts)


cursor.close()
cnx.close()

运行脚本时,它会因以下错误&#39; d

而停止
Traceback (most recent call last):
  File "./mysql-test.py", line 18, in <module>
    cursor.execute("USE %s",(databases[0],))
  File "/usr/lib/python2.6/site-packages/mysql/connector/cursor.py", line 491, in execute
    self._handle_result(self._connection.cmd_query(stmt))
  File "/usr/lib/python2.6/site-packages/mysql/connector/connection.py", line 635, in cmd_query
    statement))
  File "/usr/lib/python2.6/site-packages/mysql/connector/connection.py", line 553, 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 ''pdns_382'' at line 1

基于错误,我猜测它是如何从第一个查询中执行数据库名称的。任何正确方向的指针都会非常有用,因为我非常喜欢初学者。非常感谢你。

1 个答案:

答案 0 :(得分:2)

唉,execute的两个args形式支持“meta”参数,例如数据库,表格或字段的名称(粗略地,想到你不会想到的标识符)如果手动编写查询,则引用。所以,失败的声明:

cursor.execute("USE %s",(databases[0],))

需要重新编码为:

cursor.execute("USE %s" % (databases[0],))

,即execute的单个arg形式,带有字符串插值。幸运的是,这个特殊情况确实使您面临SQL注入风险,因为您只是插入来自数据库引擎的数据库名称。