sqlite3中Python的“=”与“match”的区别?
有两个类似的查询:
firstQuery = "select * from table_name where column_name = match_value"
secondQuery = "select * from table_name where column_name match match_value"
用 dbCursor.execute() 执行第一个查询时没问题,但执行第二个查询时却出现了错误:
sqlite3.OperationalError: unable to use function MATCH in the requested context
有人能告诉我这是为什么吗?谢谢。
2 个回答
2
在Python 2.7中
import sqlite3
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute("create table test(v1 text, v2 int)")
for index in range(5):
cur.execute("insert into test values(\"python ###{index}\", {index})".format(index=index))
import re
def matchPattern(pattern, value):
return bool(re.match(pattern, value)) # return true or false
# creating the 'match' function.
conn.create_function("matchPattern", 2, matchPattern)
正在运行...
i = cur.execute("select v1, v2 from test where matchPattern('python', v1)")
print i.fetchall()
# 输出 -> ["python ###1", 1), "python ###2", 2), ..., ....]
4
来自sqlite的表达式语法文档:
MATCH操作符是一种特殊的语法,用于match()这个用户自定义的函数。默认的match()函数实现会抛出一个异常,实际上没什么用。不过,扩展功能可以用更有用的逻辑来替代这个match()函数。