python - mysql查询在mysql-python中得到不同的结果

标签 python mysql mysql-python

我从两个不同的界面得到了不同的结果,据我所知是相同的查询。第一个是 mysql shell:

mysql> select * from table where sub_date > '2012-11-08' order by sub_date asc limit 1\G
*************************** 1. row ***************************
                 id: **176041922**

第二个是我放在一起的一个小函数,用于测试一个查询,该查询将根据日期时间字段“sub_date”提取一定数量的记录:

>>> r_query('>', '2012-11-08', '1')
((**18393664L**, 3, .....)

这是 python 模块:

import MySQLdb
myuser = MySQLdb.connect(host='localhost', user='myuser', passwd='mypass', db='mydatabase')
cur = myuser.cursor()

def r_query(oper, date, limit):
    cur.execute("""select * from table where sub_date %s %s order by sub_date asc limit %s""" % (oper, date, limit)) 
    result = cur.fetchall()
    print result

最佳答案

我对 python 几乎一无所知。但我很确定您需要在日期参数周围加上额外的引号,以便在查询字符串中引用它。可能更像:

cur.execute("""select * from table where sub_date %s '%s' order by sub_date asc limit %s""" % (oper, date, limit)) 

(注意第二个 %s 周围的额外引号)。

关于python - mysql查询在mysql-python中得到不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13457308/

相关文章:

PHP/MySQL : Massive SQL query or several smaller queries?

mysql - 两个表之间的简单连接

python - MySQLdb : correct SQL request to group response data

python - 使用 Cython 生成 C 代码时出现“未知类型名称”错误

python - 无法加载 PostgreSQL 的 Python 绑定(bind) - psycopg2

c# - 是否有支持嵌入 HTML 页面的跨操作系统 GUI 框架?

mysql - 如何自行加入?

python - 在 __init__() 中不创建对象的最佳方法是什么

python - mySQLdb 连接返回截断的输出

python - 从 Python 登录服务器和 MySQL