查询在MySQL工作台中有效,但在MySQL连接器中无效
我的问题是,当我尝试运行一个查询时,具体是这个:
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()
我在工作台上查看的数据在这里,虽然还有很多,但这是我测试的样本。 https://i.stack.imgur.com/sz82K.png
这是我在工作台上运行查询的结果: https://i.stack.imgur.com/1nphY.png
这是我想要的结果。我的查询为什么会失败呢?我尝试过重写查询,并手动替换查询中的确切日期,而不是使用参数注入,但似乎没有什么能解决这个问题。
1 个回答
2
拼写错误:
query = "SELECT call_start_time, call_end_time, sid FROM calls" \
^---
"WHERE call_start_time BETWEEN %s AND %s " \
^---
你在标记的位置缺少一个空格,这样会导致:
SELECT ... FROM callsWHERE
^---