c++连接sql server数据库代码
时间: 2023-08-24 15:08:33 浏览: 125
以下是一个简单的 C++ 连接 SQL Server 数据库的示例代码:
首先,你需要包含以下头文件:
```cpp
#include <iostream>
#include <windows.h>
#include <sqltypes.h>
#include <sql.h>
#include <sqlext.h>
```
然后,你需要定义连接数据库所需的一些变量,如下所示:
```cpp
SQLHANDLE sqlenvhandle;
SQLHANDLE sqlconnectionhandle;
SQLHANDLE sqlstatementhandle;
SQLRETURN retcode;
SQLCHAR retconstring[1024];
```
接下来,初始化环境句柄和连接句柄:
```cpp
SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &sqlenvhandle);
SQLSetEnvAttr(sqlenvhandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0);
SQLAllocHandle(SQL_HANDLE_DBC, sqlenvhandle, &sqlconnectionhandle);
```
然后,设置连接属性:
```cpp
SQLCHAR connectionstring[] = "DRIVER={SQL Server};SERVER=server_name;DATABASE=database_name;UID=user_name;PWD=password";
retcode = SQLDriverConnect(sqlconnectionhandle, NULL, connectionstring, SQL_NTS, retconstring, 1024, NULL, SQL_DRIVER_NOPROMPT);
if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) {
std::cout << "Connected to SQL Server successfully." << std::endl;
}
```
在连接成功后,你可以执行 SQL 查询语句,如下所示:
```cpp
SQLAllocHandle(SQL_HANDLE_STMT, sqlconnectionhandle, &sqlstatementhandle);
SQLCHAR query[] = "SELECT * FROM table_name";
retcode = SQLExecDirect(sqlstatementhandle, query, SQL_NTS);
if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) {
// 处理查询结果
}
```
最后,释放句柄和关闭连接:
```cpp
SQLFreeHandle(SQL_HANDLE_STMT, sqlstatementhandle);
SQLDisconnect(sqlconnectionhandle);
SQLFreeHandle(SQL_HANDLE_DBC, sqlconnectionhandle);
SQLFreeHandle(SQL_HANDLE_ENV, sqlenvhandle);
```
完整代码示例:
```cpp
#include <iostream>
#include <windows.h>
#include <sqltypes.h>
#include <sql.h>
#include <sqlext.h>
int main() {
SQLHANDLE sqlenvhandle;
SQLHANDLE sqlconnectionhandle;
SQLHANDLE sqlstatementhandle;
SQLRETURN retcode;
SQLCHAR retconstring[1024];
SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &sqlenvhandle);
SQLSetEnvAttr(sqlenvhandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0);
SQLAllocHandle(SQL_HANDLE_DBC, sqlenvhandle, &sqlconnectionhandle);
SQLCHAR connectionstring[] = "DRIVER={SQL Server};SERVER=server_name;DATABASE=database_name;UID=user_name;PWD=password";
retcode = SQLDriverConnect(sqlconnectionhandle, NULL, connectionstring, SQL_NTS, retconstring, 1024, NULL, SQL_DRIVER_NOPROMPT);
if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) {
std::cout << "Connected to SQL Server successfully." << std::endl;
}
SQLAllocHandle(SQL_HANDLE_STMT, sqlconnectionhandle, &sqlstatementhandle);
SQLCHAR query[] = "SELECT * FROM table_name";
retcode = SQLExecDirect(sqlstatementhandle, query, SQL_NTS);
if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) {
// 处理查询结果
}
SQLFreeHandle(SQL_HANDLE_STMT, sqlstatementhandle);
SQLDisconnect(sqlconnectionhandle);
SQLFreeHandle(SQL_HANDLE_DBC, sqlconnectionhandle);
SQLFreeHandle(SQL_HANDLE_ENV, sqlenvhandle);
return 0;
}
```
阅读全文