C++ 使用ADO 防止SQL注入过滤的代码
时间: 2024-02-18 10:01:00 浏览: 80
下面是一个使用ADO防止SQL注入过滤的C++代码示例:
```c++
#include <iostream>
#include <string>
#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF", "adoEOF")
using namespace std;
int main()
{
// 定义数据库连接
_ConnectionPtr pConn;
_CommandPtr pCmd;
_RecordsetPtr pRs;
// 建立数据库连接
HRESULT hr = pConn.CreateInstance(__uuidof(Connection));
pConn->ConnectionString = "Provider=SQLOLEDB;Data Source=(local);Initial Catalog=your_database_name;User ID=your_username;Password=your_password;";
pConn->Open("", "", "", adConnectUnspecified);
// 执行参数化查询
string username = "test' or 1=1 --";
string password = "123456";
string sql = "SELECT * FROM users WHERE username = ? AND password = ?";
hr = pCmd.CreateInstance(__uuidof(Command));
pCmd->ActiveConnection = pConn;
pCmd->CommandText = sql.c_str();
pCmd->CommandType = adCmdText;
pCmd->Parameters->Append(pCmd->CreateParameter("param1", adVarChar, adParamInput, username.length(), username.c_str()));
pCmd->Parameters->Append(pCmd->CreateParameter("param2", adVarChar, adParamInput, password.length(), password.c_str()));
pRs = pCmd->Execute(NULL, NULL, adCmdText);
// 处理查询结果
if (!pRs->adoEOF)
{
while (!pRs->adoEOF)
{
string username = (char*)(_bstr_t)pRs->Fields->GetItem("username")->Value;
string password = (char*)(_bstr_t)pRs->Fields->GetItem("password")->Value;
cout << "username: " << username << ", password: " << password << endl;
pRs->MoveNext();
}
}
// 释放连接和语句句柄
pRs->Close();
pCmd->Release();
pConn->Close();
pConn.Release();
return 0;
}
```
上述代码中,使用了ADO的_CommandPtr和_RecordsetPtr对象,通过CreateParameter函数来实现参数化查询,将用户输入的数据和SQL语句分开处理,从而避免了SQL注入攻击。同时,代码中也使用了_bstr_t类型来将COM VARIANT类型的数据转换为字符串类型。
阅读全文