MySQL查询会在Workbench中返回值,但在Python中运行时不会返回值

时间:2019-05-31 19:50:31

标签: python mysql python-3.x mysql-python

我正在Python中运行MySQL查询,以从数据库中提取数据。当我在Workbench中对其进行测试时,查询运行良好,但是当我尝试使用Python(使用mysql.connector)运行该查询时,它将返回0行。

import mysql.connector

#MySQL information
MYSQL_USER = 'xxxxxx'
MYSQL_PASSWORD = 'xxxxxx'
MYSQL_HOST = 'xxxxxx'
MYSQL_DB = 'xxxxxx'

#connect to MySQL database
mydb = mysql.connector.connect(host=MYSQL_HOST, user=MYSQL_USER, passwd=MYSQL_PASSWORD, database=MYSQL_DB)

#query to extract data
sql = ('''
    SELECT 
        name, 
        avg(traveltime), 
        avg(historicaltime), 
        avg(length), 
        avg(length)/avg(traveltime)/0.44704, ''' #0.44704 is to convert from m/s to mph
        '''avg(length)/avg(historicaltime)/0.44704, 
        (avg(historicaltime)-avg(traveltime))/avg(historicaltime) as diffperc 
    FROM 
        routes 
    WHERE 
        date(convert_tz(updatetime, 'UTC', 'EST5EDT')) = CURDATE() 
        AND hour(convert_tz(updatetime, 'UTC', 'EST5EDT')) in (6,7,8,9) 
    GROUP BY 
        name ''')

#execute query
try:
    mycursor = mydb.cursor()
    mycursor.execute(sql)
    results = mycursor.fetchall()

except Exception as ex:
    print(ex)

finally:
    mycursor.close()

在Workbench中,查询返回适当的数据,但是当在Python中运行时,如上面的代码所示,则该列表为空。

0 个答案:

没有答案