如何将变量传递给MySQL的LIMIT子句?

时间:2016-12-27 15:26:24

标签: python mysql pymysql

我正在尝试使用pymysql向Mysql数据库创建一个SELECT语句。 这是代码。我将一个变量传递给select语句,令我惊讶的是柠檬的巨大痛苦。知道我在这里缺少什么吗?

def getUrlFromDatabase(n):
    stmt = "SELECT * FROM jsonTes ORDER BY website LIMIT %s-1,1"
    cur.execute(stmt,str(n))
    return cur.fetchone()

conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='passwd', db='email_database', charset='utf8')
cur = conn.cursor()
cur.execute("USE database")

getUrlFromDatabase(0)

错误:

这是我尝试实现的目标:Return the nth record from MySQL query

pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''0'-1,1' at line 1")

3 个答案:

答案 0 :(得分:2)

MySQL中的

LIMIT采用数字参数,它们都必须是非负整数常量。您必须在Python中计算表达式,然后将整数作为单个参数传递。此外,您需要将参数放在元组中:

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()

答案 1 :(得分:0)

您没有以字符串格式传递%s的值1。 限制为Fatal signal 7 (SIGBUS), code 2, fault addr 0x8cf7ffff in tid 22666 (om.sketchcamera) [ 12-27 18:36:37.275 317: 317 W/ ] debuggerd: handling request: pid=22625 uid=10124 gid=10124 tid=22666

答案 2 :(得分:0)

你可以这样使用

ExchangeRateDatabase exchangeRateDatabase = new ExchangeRateDatabase();
Spinner mySpinner = (Spinner) findViewById(R.id.cur_from);
ArrayAdapter<String> myAdapter = new CustomizedSpinnerAdapter(
        AddSlaveActivity.this, android.R.layout.simple_spinner_item,
        exchangeRateDatabase.getCurrencies());
mySpinner.setAdapter(myAdapter);