查询适用于MySQL工作台,但不适用于MySQL连接器

时间:2014-03-05 18:42:39

标签: python mysql mysql-workbench mysql-python

所以我的问题在于,当我尝试运行查询时,这个特定的一个:

SELECT call_start_time, call_end_time, sid FROM calls WHERE (call_start_time BETWEEN
'2014-01-08 00:00:00' AND '2014-01-09 00:00:00') AND voice_info_id IS NOT NULL AND
call_start_time IS NOT NULL AND call_end_time IS NOT NULL

它在工作台中运行并返回我想要的正确数据,但是当我尝试使用MySQL连接器和Python在下面的代码中运行查询时,它会抱怨语法不正确,即使它是正确的。我仔细查看了连接器文档,我找不到任何与我正在做的事情和连接器文档上的查询数据使用连接器/ Python页面上的示例完全不同的内容。我正在使用的代码如下:

from time import *
import numpy as np
import matplotlib.pyplot as plt
import mysql.connector
from datetime import datetime
from sets import Set

config = {
    'user': 'xxxxxxxxx',
    'password': 'xxxxxxxxx',
    'host': '127.0.0.1',
    'database': 'xxxxxxxxx',
    'raise_on_warnings': True,
}

tick = set([])
epoch_start_call_set = set([])
epoch_end_call_set = set([])
from mysql.connector import errorcode
try:
    cnx = mysql.connector.connect(**config)
    cursor = cnx.cursor()
    print("DATABASE CONNECTION ESTABLISHED")
    print

    userIn = raw_input("Type Start Date (MM-DD-YYYY): ")
    userEnd = raw_input("Type End Date (MM-DD-YYYY): ")
    startdate = datetime.strptime(userIn, '%m-%d-%Y')
    enddate = datetime.strptime(userEnd, '%m-%d-%Y')
    epoch_s = mktime(startdate.timetuple())
    epoch_e = mktime(enddate.timetuple())
    while epoch_s <= epoch_e:
        current_tick = epoch_s + 60
        epoch_s += 60
        tick.add(current_tick)

    query = "SELECT call_start_time, call_end_time, sid FROM calls" \
            "WHERE call_start_time BETWEEN %s AND %s " \
            "AND voice_info_id IS NOT NULL AND call_start_time IS NOT NULL " \
            "AND call_end_time IS NOT NULL"
    cursor.execute(query, (startdate, enddate))


except mysql.connector.Error as err:
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print("Your password or username is incorrect, please try again")
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print("Your database does not exist, please try again")
    else:
        print(err)
else:
    cnx.close()

我正在查看的数据在工作台中,还有很多,但这是我正在测试的样本。 http://i.imgur.com/LzQn6py.png

这是我在workbench中运行查询时的结果: http://i.imgur.com/HFeCp9y.png

我想要的结果是什么。我的查询失败有特殊原因吗?我已经尝试重写并手动替换查询中的确切日期而不是使用参数注入,但似乎没有什么能解决它。

1 个答案:

答案 0 :(得分:2)

错别字:

query = "SELECT call_start_time, call_end_time, sid FROM calls" \
                                                              ^---
         "WHERE call_start_time BETWEEN %s AND %s " \
         ^---

你错过了指定地点的空间,产生:

SELECT ... FROM callsWHERE
                     ^---