2012-08-08 62 views
0

我刚开始为PostgreSQL数据库实现一些客户端软件。使用libpq/libpqxx输入消毒

查询将允许来自不受信任来源的输入参数。因此,我需要在实际提交之前清理我的交易。我发现this article在这方面是一个很好的阅读。

至于lib​​pq我发现PQescapeStringConn,这可能确实需要我。但是,因为我的代码将用C++编写,所以我更愿意使用libpqxx等价物。我找不到任何相关的东西。 (不过可能Escaper,但位于内部命名空间......)

我很感激任何建议最佳实践,阅读,文档链接,无论如何。

回答

1

使用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; --'