使用vs2022 连接sql server数据库的完整c语言示例代码
时间: 2024-12-17 22:24:29 浏览: 90
在Visual Studio 2022中连接SQL Server数据库,你需要使用ODBC(Open Database Connectivity)库或者ADO.NET(ActiveX Data Objects for .NET)。这里是一个使用ADO.NET的C#示例,如果你想要C语言的话,由于VS2022主要支持C++,可以参考以下C++代码,它使用了SQL Server的硫酸驱动程序(sqljdbc_auth.lib):
```cpp
#include <windows.h>
#include <iostream>
#include <sql.h>
#include <sqlext.h>
using namespace std;
int main() {
SQLHENV env; // 数据库环境
SQLHDBC dbc; // 数据库连接
SQLRETURN ret;
// 初始化环境
ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env);
if (ret != SQL_SUCCESS) {
cerr << "Error initializing environment: " << SQLGetErrorString(ret, NULL) << endl;
return 1;
}
ret = SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0);
if (ret != SQL_SUCCESS) {
cerr << "Error setting ODBC version: " << SQLGetErrorString(ret, NULL) << endl;
SQLFreeHandle(SQL_HANDLE_ENV, env);
return 1;
}
// 创建数据库连接
ret = SQLAllocHandle(SQL_HANDLE_DBC, env, &dbc);
if (ret != SQL_SUCCESS) {
cerr << "Error creating database connection: " << SQLGetErrorString(ret, NULL) << endl;
SQLFreeHandle(SQL_HANDLE_ENV, env);
return 1;
}
// 配置连接字符串
char* connStr = "Driver={SQL Server};Server=your_server_name;Database=your_database;uid=your_username;pwd=your_password;";
SQLCHAR *connStrChars = (SQLCHAR*) connStr;
// 连接到数据库
ret = SQLConnect(dbc, connStrChars, SQL_NTS, NULL, 0, NULL);
if (ret != SQL_SUCCESS) {
cerr << "Error connecting to the database: " << SQLGetErrorString(ret, NULL) << endl;
SQLDisconnect(dbc);
SQLFreeHandle(SQL_HANDLE_DBC, dbc);
SQLFreeHandle(SQL_HANDLE_ENV, env);
return 1;
}
cout << "Connected to SQL Server successfully!" << endl;
// 示例:执行查询并关闭连接
SQLHSTMT stmt;
ret = SQLAllocHandle(SQL_HANDLE_STMT, dbc, &stmt);
if (ret == SQL_SUCCESS) {
SQLCHAR sql[] = "SELECT * FROM your_table";
ret = SQLExecDirect(stmt, sql, SQL_NTS);
if (ret == SQL_SUCCESS) {
// 打印结果
// ...处理查询结果...
SQLFreeHandle(SQL_HANDLE_STMT, stmt);
} else {
cerr << "Error executing query: " << SQLGetErrorString(ret, NULL) << endl;
}
}
// 关闭连接
SQLDisconnect(dbc);
SQLFreeHandle(SQL_HANDLE_STMT, stmt);
SQLFreeHandle(SQL_HANDLE_DBC, dbc);
SQLFreeHandle(SQL_HANDLE_ENV, env);
cout << "Connection closed." << endl;
return 0;
}
```
阅读全文