lostincomputer2
lostincomputer2

Reputation: 353

python using torndb to search text

I want when user search "lost computer" then all records that has word "lost" and "computer" will be shown by using torndb python, i know it is easy just to use SQL statement AND operator, but making a dynamic query will be dangerous because of SQL injection, for example I have query below

def RedownloadListSelect(self, searchtext):
    searchtext = "%" + searchtext + "%"
    return self.db.query("SELECT * FROM RedownloadList WHERE column like %s", searchtext)

but above only capable to search the whole word which means that "lost 1 computer" or "lost 2 computer" won't be found if user search using text "lost computer". If I split the searchtext using space and concatenante it using AND, I think it allows for SQL injection so I decide to stick with torndb feature using arguments.

Anyone has any idea how to search with multiple AND operator using a single searchtext that does not expose SQL injection threat? Thanks

Upvotes: 0

Views: 395

Answers (1)

Igor Chubin
Igor Chubin

Reputation: 64613

You can do it this way:

searchtext='lost computer'
searchwords = searchtext.split()
query = "SELECT * FROM RedownloadList WHERE" + " AND ".join(["column like %s"]*len(searchwords))
self.db.query(query, searchwords)

Upvotes: 1

Related Questions