我刚刚开始为 PostgreSQL 数据库实现一些客户端软件。
查询将允许来自不受信任来源的输入参数。因此,我需要在实际提交交易之前对其进行清理。
至于libpq我发现PQescapeStringConn ,那可能确实是我需要的。但是,由于我的代码将用 C++ 编写,因此我更愿意使用 libpqxx 等效项。我找不到任何相关的东西。 (可能除了 Escaper ,但它位于内部命名空间中......)
如果您能提供有关最佳实践、阅读、文档链接等方面的任何建议,我将不胜感激。
最佳答案
使用pqxx::transaction_base::quote这是要走的路。
这是一个简单的例子:
// connection to the database
std::string login_str = "TODO: add credentials";
pqxx::connection conn(login_str);
pqxx::work txn(conn);
// a potentially dangerous input string
std::string input = "blah'; drop table persons; --";
// no proper escaping is used
std::string sql_1 = "select * from persons where lastname = '%s'";
std::cout << boost::format(sql_1) % input << std::endl;
// this is how it's done
std::string sql_2 = "select * from persons where lastname = %s";
std::cout << boost::format(sql_2) % txn.quote(input) << std::endl;
输出为:
select * from persons where lastname = 'blah'; drop table persons; --'
select * from persons where lastname = 'blah''; drop table persons; --'
供引用:
关于c++ - 使用 libpq/libpqxx 进行输入清理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11869267/