-2

I have written an sqlite3 query to execute the below,

cur.execute("select * from table where column like '%s'"% (variable1))

which gives the strings the completely match with the variable1. But I want an sqlite3 query that can show:

cur.execute("select * from table where column *contains* '%s'"% (variable1))

What query should I write find any string that contains 'variable1'.
Any help would be appreciable.

Tab Alleman
  • 31,483
  • 7
  • 36
  • 52
Nitya
  • 9
  • 2
  • 3
    Which dbms are you using of those 3? (Don't tag products not involved.) – jarlh Apr 26 '16 at 07:59
  • And what is the issue? The second statement is missing the closing double quote, but other than that, why doesn't it work? – nephlm Apr 26 '16 at 08:06
  • I am using sqlite3 database. closed the double quotes, still doesnt work. – Nitya Apr 26 '16 at 09:32

3 Answers3

0

See, LIKE functionality is simple.

If you want to search a string, you will have to place it in single quotes:

search all names starting with s

select name from names where name like 's%';

search all names ending with s

select name from names where name like '%s';

search all names that contain s

select name from names where name like '%s%';

But if you have stored your string in a variable var

You just have to do this:

select name from names where name like var;
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
MontyPython
  • 2,906
  • 11
  • 37
  • 58
0

To ignore characters, you have to put percent signs into the LIKE pattern (and double them so that the % operator does not try to replace them):

cur.execute("select * from table where column like '%%%s%%'" % (variable1))

But direct string interpolation brings formatting problems and possibly SQL injections. Better use a parameter:

cur.execute("select * from table where column like ?", ['%' + variable1 + '%'])
CL.
  • 173,858
  • 17
  • 217
  • 259
0

Try

cur.execute("""select * from table where column like '%{}%' """.format(variable))

Refer this link for sql

SQL SELECT WHERE field contains words

Community
  • 1
  • 1