获取SQL server数据库中所有表的数据 C++实现
时间: 2024-03-18 20:40:47 浏览: 18
要获取 SQL Server 数据库中所有表的数据,你可以使用 C++ 中的 ODBC API。下面是一个简单的示例代码,它会连接到一个 SQL Server 数据库,获取所有表的名称,然后针对每个表执行一个 SELECT 查询,以获取表中的所有数据。
```c++
#include <iostream>
#include <windows.h>
#include <sqlext.h>
#include <sqltypes.h>
#include <sql.h>
void showError(SQLHANDLE handle, SQLSMALLINT type) {
SQLCHAR SqlState[6], SQLStmt[100], Msg[SQL_MAX_MESSAGE_LENGTH];
SQLINTEGER NativeError;
SQLSMALLINT MsgLen;
SQLGetDiagRec(type, handle, 1, SqlState, &NativeError, Msg, sizeof(Msg), &MsgLen);
std::cerr << "SQL Error " << NativeError << " (" << SqlState << "): " << Msg << std::endl;
}
int main() {
SQLHENV env;
SQLHDBC dbc;
SQLHSTMT stmt;
SQLRETURN ret;
// Allocate an environment handle
SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env);
SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0);
// Allocate a connection handle
SQLAllocHandle(SQL_HANDLE_DBC, env, &dbc);
// Connect to the database
ret = SQLConnect(dbc, (SQLCHAR*)"MyDatabase", SQL_NTS, (SQLCHAR*)"MyUsername", SQL_NTS, (SQLCHAR*)"MyPassword", SQL_NTS);
if (ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO) {
showError(dbc, SQL_HANDLE_DBC);
return 1;
}
// Allocate a statement handle
SQLAllocHandle(SQL_HANDLE_STMT, dbc, &stmt);
// Get the list of tables in the database
ret = SQLTables(stmt, NULL, 0, NULL, 0, (SQLCHAR*)"dbo", SQL_NTS, (SQLCHAR*)"TABLE", SQL_NTS);
if (ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO) {
showError(stmt, SQL_HANDLE_STMT);
return 1;
}
// Fetch the results of the query
SQLCHAR tableName[256];
while (SQLFetch(stmt) == SQL_SUCCESS) {
SQLGetData(stmt, 3, SQL_C_CHAR, tableName, sizeof(tableName), NULL);
std::cout << "Table: " << tableName << std::endl;
// Execute a SELECT query on the table
SQLCHAR query[256];
sprintf_s((char*)query, sizeof(query), "SELECT * FROM %s", tableName);
ret = SQLExecDirect(stmt, query, SQL_NTS);
if (ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO) {
showError(stmt, SQL_HANDLE_STMT);
return 1;
}
// Fetch the results of the query
SQLCHAR columnValue[256];
SQLSMALLINT numColumns;
SQLNumResultCols(stmt, &numColumns);
while (SQLFetch(stmt) == SQL_SUCCESS) {
for (int i = 1; i <= numColumns; i++) {
SQLGetData(stmt, i, SQL_C_CHAR, columnValue, sizeof(columnValue), NULL);
std::cout << columnValue << " ";
}
std::cout << std::endl;
}
}
// Free the statement handle
SQLFreeHandle(SQL_HANDLE_STMT, stmt);
// Disconnect from the database
SQLDisconnect(dbc);
// Free the connection handle
SQLFreeHandle(SQL_HANDLE_DBC, dbc);
// Free the environment handle
SQLFreeHandle(SQL_HANDLE_ENV, env);
return 0;
}
```
注意:在此示例代码中,数据库名称为 "MyDatabase",用户名为 "MyUsername",密码为 "MyPassword"。你需要将这些值替换为你自己的数据库凭据。