Frage

I'm using pysqlite to build and search through a database of keywords + sets of URLs which correspond to each keyword. My strategy for searching the database works fine with 1 keyword, since it only requires 1 WHERE clause in the SQL statement. Something like:

  ... WHERE lexicon.word=?", keyword) 

However, I would like to match an arbitrary number of keywords to my database, which I believe would be equivalent to having several WHERE clauses with OR statements between them. Since I don't know how many keywords I'll be given, I can't assume a particular number of WHERE clauses and fill them in using the API's replacement ability.

I believe I could use Python's string insertion operation to mangle the WHERE statement with an OR statement for each keyword I find. I'm pretty sure this is quite hacky though, as it could lead to injection attack vulnerability.

I've also considered using the .executemany() function but it would run many separate selects instead of one which encompasses all WHERE clauses needed.

Is there a better way to do it than the method I mentioned with string replacement? I'm very new to SQL so please bear with me and my ignorance. Thanks.

War es hilfreich?

Lösung

An SQL query can have only a single WHERE clause, but you could concatenate multiple comparions with OR, or just use a single IN expression:

db.execute("SELECT ... WHERE lexicon.word IN (?,?,?)",
           ['Hello', 'world', 'meow'])

To construct such a statement, you need just a little bit of string handling:

keywords = ['Hello', 'world', 'meow']
sql = "SELECT ... WHERE lexicon.word IN (" + ",".join(["?"] * len(keywords)) + ")"
db.execute(sql, keywords)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top