C++封装ado连接sqlserver实现增删查改
时间: 2023-08-13 11:03:12 浏览: 196
好的,以下是一个 C++ ADO 封装示例代码,可以实现连接 SQL Server 数据库并进行增删改查操作。假设已经安装了 Microsoft ActiveX Data Objects 库。
```cpp
#include <iostream>
#include <comutil.h>
#include <windows.h>
#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF", "adoEOF")
using namespace std;
class AdoConnection
{
public:
AdoConnection()
{
CoInitialize(NULL);
try
{
//连接字符串
_bstr_t connStr = "Provider=SQLOLEDB;Data Source=yourServerName;Initial Catalog=yourDatabaseName;User ID=yourUserName;Password=yourPassword";
//创建连接对象
m_pConn = ADODB::_ConnectionPtr("ADODB.Connection");
//打开连接
m_pConn->Open(connStr, "", "", ADODB::adModeUnknown);
}
catch (_com_error& e)
{
cerr << "Error: " << e.ErrorMessage() << endl;
}
}
~AdoConnection()
{
try
{
//关闭连接
m_pConn->Close();
}
catch (_com_error& e)
{
cerr << "Error: " << e.ErrorMessage() << endl;
}
CoUninitialize();
}
bool executeSql(const _bstr_t& sql)
{
try
{
//执行 SQL 语句
m_pConn->Execute(sql, NULL, ADODB::adCmdText);
return true;
}
catch (_com_error& e)
{
cerr << "Error: " << e.ErrorMessage() << endl;
return false;
}
}
ADODB::_RecordsetPtr query(const _bstr_t& sql)
{
try
{
//查询数据
ADODB::_RecordsetPtr pRs("ADODB.Recordset");
pRs->Open(sql, m_pConn.GetInterfacePtr(), ADODB::adOpenKeyset, ADODB::adLockOptimistic, ADODB::adCmdText);
return pRs;
}
catch (_com_error& e)
{
cerr << "Error: " << e.ErrorMessage() << endl;
return NULL;
}
}
private:
ADODB::_ConnectionPtr m_pConn;
};
int main()
{
AdoConnection conn;
//查询数据
_bstr_t sql = "SELECT * FROM yourTableName";
ADODB::_RecordsetPtr pRs = conn.query(sql);
if (pRs != NULL)
{
while (!pRs->adoEOF)
{
cout << pRs->Fields->GetItem("columnName1")->Value.bstrVal << " " << pRs->Fields->GetItem("columnName2")->Value.bstrVal << endl;
pRs->MoveNext();
}
pRs->Close();
}
//插入数据
sql = "INSERT INTO yourTableName (columnName1, columnName2) VALUES ('value1', 'value2')";
conn.executeSql(sql);
//更新数据
sql = "UPDATE yourTableName SET columnName1 = 'newValue1' WHERE columnName2 = 'value2'";
conn.executeSql(sql);
//删除数据
sql = "DELETE FROM yourTableName WHERE columnName1 = 'value1'";
conn.executeSql(sql);
return 0;
}
```
请注意替换代码中的数据库连接信息和 SQL 语句中的表名、列名和值。另外,使用 `AdoConnection` 类来封装连接,可以提高代码的复用性和可维护性。
阅读全文