在 python 上使用 apsw 在 SQLite 中搜索值

Searching values in SQLite, with apsw, on python

为什么这个代码 returns 行 'p',8,9 当我要求它 returns 只有第一个元素大于然后是 3 的行?此行的第一个元素是 'p'。 我注意到这个方法与 int 一起工作很好,但是如果比较的元素是 str,就会发生这种情况。为什么 ?以及如何修复它(例如,我怎样才能只获得某些元素大于 3 的行)? 我更想知道为什么会这样。

代码:

import apsw


connection=apsw.Connection("database01")
cursor=connection.cursor()
cursor.execute("create table foo(a,b,c)")
cursor.execute("insert into foo values(1,2,3);insert into foo values(4,5,6);insert into foo values(7,8,9);insert into foo values('p',8,9)")


for x,y,z in cursor.execute("select a,b,c from foo"):
    print (cursor.getdescription())  # shows column names and declared types
    print (x,y,z)


def rowtrace(*results):
    """Called with each row of results before they are handed off.  You can return None to
    cause the row to be skipped or a different set of values to return"""
    print ("Row:",results)
    return results

cursor.setrowtrace(rowtrace)
for row in cursor.execute("select a,b from foo where a>3"):
     pass

输出:

(('a', None), ('b', None), ('c', None))
1 2 3
(('a', None), ('b', None), ('c', None))
4 5 6
(('a', None), ('b', None), ('c', None))
7 8 9
(('a', None), ('b', None), ('c', None))
p 8 9
Row: (<apsw.Cursor object at 0x7fab057f92b0>, (4, 5))
Row: (<apsw.Cursor object at 0x7fab057f92b0>, (7, 8))
Row: (<apsw.Cursor object at 0x7fab057f92b0>, ('p', 8))

来源:http://www.cesarkallas.net/arquivos/apostilas/python/exemplos/APSW%20-%20Another%20Python%20SQLite%20Wrapper.htm

可以在 a 列的 sqlite3 doc on Comparison Expressions. It matches the Comparison Example 中找到“原因”。

-- Because column "a" has text affinity, numeric values on the
-- right-hand side of the comparisons are converted to text before
-- the comparison occurs.
SELECT a < 40, a < 60, a < 600 FROM t1;
0|1|1

选项是在比较之前将 a 转换为整数,即 WHERE cast(a as int) > 3。这只是一个选项,因为它不是一个完美的解决方案,具体取决于用例。另一种选择是将 a 限制在高端,例如 WHERE a between 3 and 99999999;又不是一个完美的解决方案。