sprintf(query, "SELECT username, msg, ts, lat, lon FROM tweet WHERE msg LIKE '%'%s'%' ORDER BY ts DESC", keyword);
我这样做的方式是给我错误。我该如何格式化'%关键字%'使用printf进入SQL?
答案 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注入攻击。请改用参数化查询。