How To Pass A Variable To MySQL's LIMIT Clause?
I am trying to make a SELECT statement to Mysql datbase using pymysql. This is the code. I am passing a variable to the select statement, and to my surprise this is a huge pain in
Solution 1:
LIMIT
in MySQL takes numeric arguments, which must both be nonnegative integer constants. You have to calculate the expression in Python and then pass the integer as a single parameter. Also, you need to put the parameter in a tuple:
def getUrlFromDatabase(n):
stmt = "SELECT * FROM jsonTes ORDER BY website LIMIT %s, 1"
cur.execute(stmt, (n-1 if n > 0 else 0,))
return cur.fetchone()
Solution 2:
You are not passing the value 1 for %s in the string format.
stmt = "SELECT * FROM jsonTes ORDER BY website LIMIT %s" %n
for limit n
Solution 3:
you can use like that
def getUrlFromDatabase(n):
stmt = "SELECT * FROM jsonTes ORDER BY website LIMIT {}, 1"
cur.execute(stmt.format(n-1 if n > 0 else n))
return cur.fetchone()
Post a Comment for "How To Pass A Variable To MySQL's LIMIT Clause?"