Python MySQL Parameter Query Programming Error: 1064 (42000)
Python MySQL Parameter Query Programming Error: 1064 (42000)
我想使用 python 程序查询 MySQL 表,但出现此错误:
ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''10' OFFSET '0'' at line 1
令人困惑的是,当我不使用变量时,查询运行完美,如下所示:
cur = connection.cursor()
query = "SELECT * FROM DB.Table LIMIT 10 OFFSET 0"
cur.execute(query)
records = cur.fetchall()
for record in records:
print(record)
但我需要 select 逐批处理数据,并且我必须在 for 循环中执行上述命令。我需要定义变量。但是我得到了错误 1064。这是有错误的代码:
i = 0
p = str(i)
j = 10
q = str(j)
cur = connection.cursor()
query = "SELECT * FROM DB.Table LIMIT %s OFFSET %s"
cur.execute(query,(q,p,))
records = cur.fetchall()
for record in records:
print(record)
感谢您的帮助。
您可以使用 cur.execute(query % (q,p))
或
query = "SELECT * FROM DB.Table LIMIT {} OFFSET {}"
cur.execute(query.format(q, p))
简单地说,不要将参数化值转换为字符串,因为错误显示单引号:
i = 0
j = 10
cur = connection.cursor()
query = "SELECT * FROM DB.Table LIMIT %s OFFSET %s"
cur.execute(query, (j, i))
我想使用 python 程序查询 MySQL 表,但出现此错误:
ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''10' OFFSET '0'' at line 1
令人困惑的是,当我不使用变量时,查询运行完美,如下所示:
cur = connection.cursor()
query = "SELECT * FROM DB.Table LIMIT 10 OFFSET 0"
cur.execute(query)
records = cur.fetchall()
for record in records:
print(record)
但我需要 select 逐批处理数据,并且我必须在 for 循环中执行上述命令。我需要定义变量。但是我得到了错误 1064。这是有错误的代码:
i = 0
p = str(i)
j = 10
q = str(j)
cur = connection.cursor()
query = "SELECT * FROM DB.Table LIMIT %s OFFSET %s"
cur.execute(query,(q,p,))
records = cur.fetchall()
for record in records:
print(record)
感谢您的帮助。
您可以使用 cur.execute(query % (q,p))
或
query = "SELECT * FROM DB.Table LIMIT {} OFFSET {}"
cur.execute(query.format(q, p))
简单地说,不要将参数化值转换为字符串,因为错误显示单引号:
i = 0
j = 10
cur = connection.cursor()
query = "SELECT * FROM DB.Table LIMIT %s OFFSET %s"
cur.execute(query, (j, i))