Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with regexp python and sqlite

I try to check a string with a pattern using a regex with python on a sqlite database. I have problem when I try de search string having " with a patern using " For exemple:

cur.execute("insert into articles(id,subject) values (1,'aaa\"test\"')")
cur.execute("select id,subject from articles where id = 1")
print (cur.fetchall())

cur.execute("select subject from articles where  subject regexp '\"test\"' ")
print (cur.fetchall())

I should \" before regexp other way compiler dont like... syntaxe error

[(1, 'aaa"test"')]
[] <????? should found 

Somebody know how to do that ?

My regexp function :con.create_function("regexp", 2, regexp)

like image 408
pr0m Avatar asked Mar 19 '11 22:03

pr0m


People also ask

Can you use regex in SQLite?

SQLite does not contain regular expression functionality by default. It defines a REGEXP operator, but this will fail with an error message unless you or your framework define a user function called regexp() .

Is SQLite good for Python?

SQLite3 can be integrated with Python using sqlite3 module, which was written by Gerhard Haring. It provides an SQL interface compliant with the DB-API 2.0 specification described by PEP 249. You do not need to install this module separately because it is shipped by default along with Python version 2.5.

Does pandas work with SQLite?

sqlite3 provides a SQL-like interface to read, query, and write SQL databases from Python. sqlite3 can be used with Pandas to read SQL data to the familiar Pandas DataFrame. Pandas and sqlite3 can also be used to transfer between the CSV and SQL formats.

What is Fetchall in sqlite3?

The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows it returns the remaining ones). The fetchone() method fetches the next row in the result of a query and returns it as a tuple.


1 Answers

Use parametrized sql. Then you don't need to escape the quotes yourself:

import sqlite3
import re

def regexp(expr, item):
    reg = re.compile(expr)
    return reg.search(item) is not None

conn = sqlite3.connect(':memory:')
conn.create_function("REGEXP", 2, regexp)
cursor = conn.cursor()
cursor.execute('CREATE TABLE foo (bar TEXT)')
cursor.executemany('INSERT INTO foo (bar) VALUES (?)',[('aaa"test"',),('blah',)])
cursor.execute('SELECT bar FROM foo WHERE bar REGEXP ?',['"test"'])
data=cursor.fetchall()
print(data)

yields

[(u'aaa"test"',)]
like image 142
unutbu Avatar answered Sep 30 '22 09:09

unutbu