wisdom
wisdom

Reputation: 442

Like statement in DataBase with Python

I'm still learning Python as great simple programming language, the problem came with DataBase , I'm using MySQL to build it then I want to Select some tuples from Python code as I did write the query as following:

Q = "INSERT INTO contacts (FirstName,LastName,phone,mobile,email,address) VALUES('%s','%s','%s','%s','%s','%s') "% \
            (FN,LN,phone,Mobile,email,address)

becuase of using variables and it's OK.
but If I want to use (LIKE'') statement in query I get into quotations troubles ! as following:

    Q = "SELECT LastName FROM contacts WHERE phone LIKE '_'%s'%'" %\
            (phone)

What can I do to solve this problem, any hints ?

Upvotes: 0

Views: 2143

Answers (1)

Emil Vikström
Emil Vikström

Reputation: 91983

Use prepared statements and avoid the troubles of string formatting:

pattern = "_" + phone + "%"
cursor.execute("SELECT LastName FROM contacts WHERE phone LIKE %s", (pattern,))

If you don't want to use prepared statements, or if you stumble upon this problem in other cases, switch to using str.format (but read about SQL injections before doing this):

Q = "SELECT LastName FROM contacts WHERE phone LIKE '_{0}%'".format(phone)

Or combine the two:

pattern = "_{0}%".format(phone)
cursor.execute("SELECT LastName FROM contacts WHERE phone LIKE %s", (pattern,))

Upvotes: 5

Related Questions