在sqlite3,Python中“=”和“匹配”之间的区别?

时间:2011-07-14 09:35:29

标签: python select sqlite

两个类似的查询:

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 个答案:

答案 0 :(得分:4)

来自sqlite expression syntax文档:

  

MATCH运算符是match()应用程序定义函数的特殊语法。 默认的match()函数实现会引发异常并且对任何事情都没有用。但扩展可以使用更有用的逻辑覆盖match()函数。

答案 1 :(得分: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()

#print - > [“python ### 1”,1),“python ### 2”,2),...,....]