Xupacuma
Xupacuma

Reputation: 11

Python: encoding in Sqlite query

I have a problem with encoding in SQLite (sqlite3 module in Python 2.7). I have a table with two columns: (text_number int, word text). In word we have numbers, English and Russian words.

I need to find all strings in table where word = search_word.

When search_word is number, I have no problems:

search_word = '146'
lenta_u_w = c.execute('SELECT * FROM lenta WHERE word = ' + search_word)
for w in lenta_u_w :
    print w

and gives something like (361, u'146').

But, any other kind of characters do not work:

search_word = u'android'
lenta_u_w = c.execute('SELECT * FROM lenta WHERE word = ' + search_word)
for w in lenta_u_w :
    print w
>>>lenta_u_w = c.execute('SELECT * FROM lenta WHERE word = ' + search_word)
OperationalError: no such column: android

I try many versions of decode and so on, but nothing can help me.

Upvotes: 1

Views: 656

Answers (1)

seliopou
seliopou

Reputation: 2916

Use parameters when constructing and executing your queries, which will do the appropriate quoting and escaping for you:

c.execute('SELECT * FROM lenta WHERE word = ?', (search_word,))

See the documentation for the Cursor class in the sqlite3 package for more details.

Upvotes: 1

Related Questions