[英]why this insert gives syntax error
res = PQexec(conn,"INSERT INTO worker (fullname,type) VALUES ('"ptr"',"type")");
type
是整数, ptr
是字符串。 这里有什么问题? 我该如何解决? “”有问题吗?
代替
res = PQexec(conn,"INSERT INTO worker (fullname,type) VALUES ('"ptr"',"type")");
使用stringstream创建字符串
#include <sstream>
std::stringstream ss;
ss << "INSERT INTO worker (fullname,type) VALUES ('" << ptr << "'," << type << ")";
res = PQexec(conn, ss.str().c_str() );
C ++不会自动将值转换为字符串。 要构建字符串,请使用cldtrap的答案中所示的std::stringstream
。
但是,除非您完全确定变量是安全的,以防注入攻击,否则最好将值作为参数传递,而不是将其直接注入到SQL中,例如:
std::stringstream ss;
ss << type;
std::string type_string = ss.str(); // or std::to_string(type) if available
const char * values[] = {ptr, type_string.c_str()};
res = PQexecParams(conn, "INSERT INTO worker (fullname,type) VALUES ($1,$2)",
2, NULL, values, NULL, NULL, 0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.