我仍在学习Python作为一种简单的编程语言,问题来自DataBase,我使用MySQL构建它然后我想从Python代码中选择一些元组,因为我编写了如下查询:
Q = "INSERT INTO contacts (FirstName,LastName,phone,mobile,email,address) VALUES('%s','%s','%s','%s','%s','%s') "% \
(FN,LN,phone,Mobile,email,address)
因为使用变量而且没关系 但如果我想在查询中使用(LIKE'')语句,我会陷入报价麻烦!如下:
Q = "SELECT LastName FROM contacts WHERE phone LIKE '_'%s'%'" %\
(phone)
我可以做些什么来解决这个问题,任何提示?
答案 0 :(得分:4)
使用prepared statements并避免字符串格式化的麻烦:
pattern = "_" + phone + "%"
cursor.execute("SELECT LastName FROM contacts WHERE phone LIKE %s", (pattern,))
如果您不想使用预准备语句,或者在其他情况下偶然遇到此问题,请切换到使用str.format(但请在执行此操作之前阅读SQL injections):
Q = "SELECT LastName FROM contacts WHERE phone LIKE '_{0}%'".format(phone)
或者将两者结合起来:
pattern = "_{0}%".format(phone)
cursor.execute("SELECT LastName FROM contacts WHERE phone LIKE %s", (pattern,))