简体   繁体   中英

mysql query getting different results in mysql-python

I'm getting different results with what I understand to be the same query from two different interfaces. The first is a mysql shell:

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

The second is a little function I put together to test a query that would pull a certain amount of records based on the datetime field "sub_date":

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

Here's the python module:

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

I know nearly nothing about python. But I'm pretty sure you need to put extra quotes around your date parameter in order for it to be quoted in the query string. Probably more like:

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

(note the extra quotes around the second %s).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM