如何使用WHERE LIKE SQL子句?

时间:2014-05-19 04:58:55

标签: sql c

sprintf(query, "SELECT username, msg, ts, lat, lon FROM tweet WHERE msg LIKE '%'%s'%' ORDER BY ts DESC", keyword);

我这样做的方式是给我错误。我该如何格式化'%关键字%'使用printf进入SQL?

2 个答案:

答案 0 :(得分:3)

如果我理解SQL Query语句是正确的,当keyword的值为NBA时,您希望查询字符串看起来像:

"SELECT username, msg, ts, lat, lon FROM tweet WHERE msg LIKE '%NBA%' ORDER BY ts DESC"

在这种情况下,sprintf语句的格式必须是:

"SELECT username, msg, ts, lat, lon FROM tweet WHERE msg LIKE '%%%s%%' ORDER BY ts DESC"

答案 1 :(得分:2)

您需要通过加倍%%

来引用百分号
sprintf(query, "SELECT username, msg, ts, lat, lon FROM tweet WHERE msg LIKE '%%%s%%' ORDER BY ts DESC", keyword);
                                                                              ^^  ^^

如上所述:连接字符串容易出错,可能会受到SQL注入攻击。请改用参数化查询。