【问题标题】:Not able to parameterize LIMIT and OFFSET in sqlite3无法在 sqlite3 中参数化 LIMIT 和 OFFSET
【发布时间】:2018-11-06 03:38:50
【问题描述】:

为什么下面的代码给出语法错误“sqlite3.OperationalError: near "?": syntax error

import sqlite3

connection = sqlite3.connect('data.db')

cursor = connection.cursor()

table = "device_store"
uuid = "bbebe39e-fe2e-4817-b022-a3ef13bd6283"
page = 1
POSTS_PER_PAGE = 10
query = "SELECT * FROM ? WHERE uuid=? LIMIT ? OFFSET ?"
result = cursor.execute(query, (table, uuid, POSTS_PER_PAGE, 0))
rows = result.fetchall()
connection.close()
print("==>> Printing rows <<==")
print(rows)

【问题讨论】:

    标签: python-3.x sqlite


    【解决方案1】:

    错误是由FROM ? 中的占位符引起的,而不是其他的。表名不能作为参数传递,它们必须在语句中进行硬编码。

    【讨论】:

    • 您好,我可以在其他查​​询中将表名作为参数传递。只有在向查询中添加“LIMIT”和“OFFSET”选项后,我才会看到此错误。
    • @ios_mxe 我希望看到一个允许您使用表名作为参数的查询,因为这不是 sqlite(或我熟悉的任何 RDMS)的工作方式。语句编译成内部字节码时需要知道表名,执行prepared statement时不能给出。与列名相同。
    • @classmethod def find_by_uuid_distinct(cls, uuid, table): connection = sqlite3.connect('data.db') cursor = connection.cursor() query = "SELECT DISTINCT domain FROM ? WHERE uuid= ?” result = cursor.execute(query, (table, uuid)) rows = result.fetchall() connection.close() print("==>> 打印唯一域名的行
    • 在上面显示的类方法中,我将“table”作为参数传入,然后在 sqlite 查询中替换该参数。这部分代码运行良好。
    • 别介意肖恩!这个 sn-p 是一个同事早些时候写的死代码。我用了它,它已经造成了抵押品。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-27
    • 2020-08-19
    • 2015-07-24
    • 2012-08-25
    相关资源
    最近更新 更多