PostgresSQL - SQL Ready 语句与字符串转义,防止 SQL 注入攻击

PostgresSQL - SQL Prepared Statement vs String Escaping preventing SQL injection attacks

本文关键字:SQL 防止 注入 转义 攻击 Ready 语句 PostgresSQL 字符串      更新时间:2023-10-16

嗨,我正在使用libpqxx编写一个c ++应用程序,将行插入Postgres SQL表中,并且正在写入的数据是用户输入的,因此我需要防范SQL注入攻击。从我在网上看到的情况来看,我可以采取两种方法:

  1. 准备好的声明
std::string name_str = "Bob";            \! User input unsafe!!
std::string email_str = "bob@gmail.com"; \! User input unsafe!!
pqxx::connection con(c_string);
std::string insert_str = "INSERT INTO users(name, email) VALUES ($1, $2)";
con.prepare("insert_to_users", insert_str);
pqxx::work insert_work(con);
insert_work.exec_prepared("insert_to_users", name_str, email_str)
  1. 字符串转义
std::string name_str = "Bob";            \! User input unsafe!!
std::string email_str = "bob@gmail.com"; \! User input unsafe!!
pqxx::connection con(c_string);
pqxx::work insert_work(con);
std::string insert_str = "INSERT INTO users(name, email)"
"VALUES ('" + insert_work.esc(name_str) + "' , '" + insert_work.esc(email_str) + "')";
insert_work.exec(insert_str)

我的应用程序不会使数据库连接保持活动状态,因此预准备语句只会使用一次然后销毁,那么使用预准备语句是否过分?

字符串转义是否提供针对所有 SQL 注入漏洞的保护?还是有更好的方法?

我的应用程序不会使数据库连接保持活动状态,因此预准备语句只会使用一次

如果您担心性能,则应修复此一次性连接问题。如果你不担心性能,那你为什么要关心准备好的陈述是否"矫枉过正"呢?

虽然两者都应该有效,但第一个更干净,将来不太可能有人搞砸。