CADOConn conn; std::wstring strConn = L"Provider=SQLOLEDB;Data Source=127.0.0.1;Initial Catalog=SQL_PLC;User Id=sa;Password=bme12345;"; std::wstring strSQL; if (!conn.Open(strConn)) { std::cerr << "Failed to connect to database!" << std::endl; return -1; } // 插入数据 strSQL = L"INSERT INTO plcdata (出水压力,瞬时流量,总流量,当日运行次数,运行总次数) VALUES (2,2,5,2,0)"; if (!conn.Add(strSQL)) { std::cerr << "Failed to insert data!" << std::endl; } 参数化查询
时间: 2024-03-03 12:48:54 浏览: 66
参数化查询可以有效避免SQL注入攻击,同时也能提高查询效率和安全性。修改上述代码以使用参数化查询,可以参考以下示例:
```
CADOConn conn;
std::wstring strConn = L"Provider=SQLOLEDB;Data Source=127.0.0.1;Initial Catalog=SQL_PLC;User Id=sa;Password=bme12345;";
std::wstring strSQL;
if (!conn.Open(strConn))
{
std::cerr << "Failed to connect to database!" << std::endl;
return -1;
}
// 插入数据
strSQL = L"INSERT INTO plcdata (出水压力,瞬时流量,总流量,当日运行次数,运行总次数) VALUES (?, ?, ?, ?, ?)";
CADOCommand cmd(&conn);
cmd.SetCommandText(strSQL.c_str());
cmd.AddParameter(L"出水压力", adInteger, adParamInput, 0, 2);
cmd.AddParameter(L"瞬时流量", adInteger, adParamInput, 0, 2);
cmd.AddParameter(L"总流量", adInteger, adParamInput, 0, 5);
cmd.AddParameter(L"当日运行次数", adInteger, adParamInput, 0, 2);
cmd.AddParameter(L"运行总次数", adInteger, adParamInput, 0, 0);
if (!cmd.Execute())
{
std::cerr << "Failed to insert data!" << std::endl;
}
```
以上代码中,使用参数占位符 "?" 替换了具体数值,同时在 CADOCommand 对象中添加了对应的参数,类型为 adInteger,表示整型参数。在执行 cmd.Execute() 时,会自动将参数值填充到 SQL 语句中,然后执行插入操作。
阅读全文