使用C++Mysql驱动程序转义字符串
Escaping strings with the C++ Mysql Driver
我在使用mysql c++驱动程序转义字符串时遇到问题。通过阅读mysql论坛,我发现了一个小例子,下面的方法似乎是正确的。然而,动态转换似乎不起作用。有人有什么见解吗?谢谢
p.S."conn"是我的Connection对象。它保证在这一点上被分配,所以它不是问题所在。
EDIT:添加类构造函数以完成代码示例。
DbConnector::DbConnector(const ns4__ServerHostResponse &response)
{
try
{
driver = get_driver_instance();
conn.reset(
driver->connect(boost::str(boost::format("tcp://%1%:3306") % response.DatabaseHostName), response.Username, response.Password));
conn->setSchema(response.DbSchema);
query << "";
}
catch(std::exception &ex)
{
throw CustomException(boost::str(boost::format("Unable to connect to database: %1%") % response.DbSchema), ex.what());
}
catch(...)
{
throw StokedTcpException(boost::str(boost::format("Unable to connect to database: %1%") % response.DbSchema));
}
}
void DbConnector::EscapeString(std::string &s) {
if (conn)
{
std::shared_ptr<sql::mysql::MySQL_Connection> mysqlConn(dynamic_cast<sql::mysql::MySQL_Connection*>(conn.get()));
if (mysqlConn)
s = mysqlConn->escapeString(s);
else
throw CustomException("Cannot allocate connection object to escape mysql string!");
}
}
我知道这可能太晚了,但作为您的参考,转换失败了,因为您可能没有包括以下内容:
#include <mysql_connection.h>
它不是C++中sql::connector的部分,而是MySQL的底层C库。
在Linux Debian中,它位于以下位置:
/usr/include/mysql_connection.h
在某些情况下,它与mysql连接器一起提供。如果你把它包括在内,那么下变频效果很好:
sql::mysql::MySQL_Connection * mysql_conn = dynamic_cast<sql::mysql::MySQL_Connection*>(con);
std::string escaped = mysql_conn->escapeString( query );
stmt->execute( escaped );
希望它能帮助任何陷入同样问题的人。
EDIT:实际上,您不应该像上面的例子所示那样转义查询,而是应该转义特定的字符串。转义查询可能会转义值周围的单引号。
不知道准备好的语句转义是如何进行的,因为我曾尝试在sql::connector
相关文章:
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 将 NULL 与 C 的字符* 字符串一起使用
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- 无法将常量字符字符串传递给模板类
- 为什么当我从 cin 阅读时转义字符不起作用?
- 如何组合一个宽字符字符串,中间插入一些空字符
- 转义std::字符串中的特殊字符
- 在QLineEdit中显示和编辑转义字符
- std::regex_error语言 - 意外的转义字符
- 如何将二维数组类型字符(字符串)作为函数参数传递?
- 从给定索引返回子字符字符串的函数
- 字符 [](c 字符串)的初始化标准
- LPCWSTR 查找和替换为转义字符
- 将带有转义字符的大字符串转换为字节数组
- 由转义字符组成的字符串文字的大小
- 在字符串行中查找转义字符
- 定义 std::字符串 C++不带转义字符
- 打印不带转义字符的字符串
- 在.pro文件QT中定义带有转义字符的字符串宏
- 在c++字符串字面量中使用的可接受的自定义转义字符是什么?