I use python3 to search an exact word in a sqlite3 database. When I do it with SQLite database browser it works perfectly. But when I do it with python3, it throws: sqlite3.OperationalError: user-defined function raised exception. (I will use this code for an app to search in a treeview)
Here is the code:
import sqlite3
import re
def regexp(expr, item):
reg = re.compile(expr)
return reg.search(item) is not None
conn = sqlite3.connect('/database.db')
conn.create_function("REGEXP", 2, regexp)
cursor = conn.cursor()
cursor.execute('SELECT * FROM table WHERE column REGEXP ?',['(?i)(?<=\s|^|\W)word(?=\s|$|\W)'])
data=cursor.fetchall()
print(data)
I updated my code as:
import sqlite3
import re
def regexp
def regexp(expr, item):
try:
pattern = re.compile(expr, re.I)
return re.search(pattern, str) is not None
except Exception as e:
print(e)
conn = sqlite3.connect('database.db')
conn.create_function("regexp", 2, regexp)
cursor = conn.cursor()
try:
cursor.execute(r'SELECT * FROM table WHERE column REGEXP ?',[r'(?i)(?<=\s|^|\W)word(?=\s|$|\W)'])
data=cursor.fetchall()
print(data)
except Exception as e:
print(e)
And it throws : look-behind requires fixed-width pattern