当使用占位符时,Python Sqlite3执行时会被执行falied'

时间:2017-02-18 08:46:15

标签: python sqlite sqlalchemy

代码如下,在'顺序中看起来像sqlite3 substitution语法有一些bug。

import sqlite3

conn = sqlite3.connect('student.db')
cur = conn.execute('select * from students order by :sort :order limit 10', dict(sort='age', order='desc'))

# This will get
# OperationalError: near ":order": syntax error

# If you do this, the result is NOT sorted by the age column
cur = conn.execute('select * from students order by :sort limit 10', dict(sort='age'))

# I don't know why

1 个答案:

答案 0 :(得分:3)

电话

cur = conn.execute('select * from students order by :sort :order limit 10', dict(sort='age', order='desc'))

导致查询

select * from students order by 'age' 'desc' limit 10

这将返回按 literal 字符串'age'排序的表的内容,这对所有行都是相同的,所以什么都不做。但是'desc'无效,必须desc没有引号,这就是您收到错误的原因。

您应尽可能使用查询参数,但查询参数不能用于提供表名和列名称。

在这种情况下,您需要使用纯字符串格式来构建查询。如果您的参数(在这种情况下是排序标准和顺序)来自用户输入,您需要先验证它,例如:

valid_column_names = {'age', ...}
valid_sort_orders = {'asc', 'desc'}
sort = get_sort_column_from_user_input()
order = get_order_from_user_input()
# use user supplied value if valid, else use a default
sort = sort if sort in valid_column_names else 'age'
# validate sort orders
order = order if order.lower() in valid_sort_orders else 'asc'

query = 'select * from students order by {sort} {order} limit 10'.format(sort=sort, order=order)
cursor.execute(query)