c++ - 使用 libpq/libpqxx 进行输入清理

标签 c++ libpq libpqxx

我刚刚开始为 PostgreSQL 数据库实现一些客户端软件。

查询将允许来自不受信任来源的输入参数。因此,我需要在实际提交交易之前对其进行清理。

至于lib​​pq我发现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/

相关文章:

c++ - 使用 NASM/Linux 的定时器

c++ - 未定义对 PQfinish 的引用,即使包含库等

PostgreSQL、libpq/C、更新参数

postgresql - postgres 中的 View 路径(其他全局可用表的私有(private)/个人版本)

c++ - 我的向量化 xorshift+ 不是很随机

c++ - C++ 构造函数中的损坏

c++ - 不处理指针时调用子类(虚拟)函数(后期绑定(bind))

c++ - 使用 libpq 组织 PostgreSQL 数据库连接参数?

c++ - 使用 libpqxx 连接到 Postgres 数据库

c++ - Libpqxx 连接池