c++ ado封装sqlserver实现增删查改
时间: 2023-08-01 11:15:16 浏览: 50
C++、MFC连接MYSQL实现增删改查
以下是使用 C++ 和 ADO 封装 SQL Server 实现增删查改的示例代码:
```cpp
#include <iostream>
#include <string>
#include <Windows.h>
#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF", "adoEOF")
using namespace std;
class Database {
private:
_ConnectionPtr conn; // ADO 连接对象
public:
// 构造函数,连接数据库
Database(string server, string database, string username, string password) {
try {
conn.CreateInstance(__uuidof(Connection));
conn->ConnectionString = "Provider=SQLOLEDB.1;Data Source=" + server + ";Initial Catalog=" + database + ";User ID=" + username + ";Password=" + password + ";";
conn->Open("", "", "", adConnectUnspecified);
}
catch (_com_error e) {
cerr << "Connect to database failed: " << e.ErrorMessage() << endl;
exit(1);
}
}
// 析构函数,关闭连接
~Database() {
conn->Close();
}
// 执行查询语句,并返回查询结果集
_RecordsetPtr query(string sql) {
_RecordsetPtr rs; // ADO 记录集对象
try {
rs.CreateInstance(__uuidof(Recordset));
rs->Open(sql.c_str(), conn.GetInterfacePtr(), adOpenStatic, adLockOptimistic, adCmdText);
}
catch (_com_error e) {
cerr << "Query failed: " << e.ErrorMessage() << endl;
exit(1);
}
return rs;
}
// 执行增、删、改语句,并返回受影响的行数
int execute(string sql) {
int rows = 0; // 受影响的行数
try {
_variant_t rowsAffected;
conn->Execute(sql.c_str(), &rowsAffected, adExecuteNoRecords);
rows = rowsAffected.intVal;
}
catch (_com_error e) {
cerr << "Execute failed: " << e.ErrorMessage() << endl;
exit(1);
}
return rows;
}
};
int main() {
// 连接数据库
Database db("localhost", "test", "sa", "123456");
// 查询数据
_RecordsetPtr rs = db.query("SELECT * FROM users");
while (!rs->adoEOF) {
cout << rs->Fields->GetItem("id")->Value.intVal << ", " << (char*)(_bstr_t)rs->Fields->GetItem("name")->Value << ", " << rs->Fields->GetItem("age")->Value.intVal << endl;
rs->MoveNext();
}
// 插入数据
int rows = db.execute("INSERT INTO users (name, age) VALUES ('Tom', 18)");
cout << "Inserted " << rows << " rows." << endl;
// 更新数据
rows = db.execute("UPDATE users SET age = 20 WHERE name = 'Tom'");
cout << "Updated " << rows << " rows." << endl;
// 删除数据
rows = db.execute("DELETE FROM users WHERE name = 'Tom'");
cout << "Deleted " << rows << " rows." << endl;
return 0;
}
```
注意,在运行该示例代码前,需要先安装 Microsoft ActiveX Data Objects(ADO)库,并将 `msado15.dll` 文件路径修改为本地安装路径。另外,示例代码仅供参考,实际使用时需要根据具体情况进行调整。
阅读全文