获取SQL server数据库中表的列名C++实现
时间: 2024-03-18 16:40:33 浏览: 69
你可以使用 SQL Server 的系统表来获取表的列名。以下是一个 C++ 示例代码,用于获取表名为 "myTable" 的列名:
```c++
#include <iostream>
#include <sql.h>
#include <sqlext.h>
#include <string>
using namespace std;
int main() {
// Declare variables
SQLHANDLE sqlEnvHandle = NULL;
SQLHANDLE sqlConnHandle = NULL;
SQLHANDLE sqlStmtHandle = NULL;
SQLRETURN retCode = 0;
string tableName = "myTable";
// Allocate environment handle
retCode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &sqlEnvHandle);
// Set the ODBC version environment attribute
retCode = SQLSetEnvAttr(sqlEnvHandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0);
// Allocate connection handle
retCode = SQLAllocHandle(SQL_HANDLE_DBC, sqlEnvHandle, &sqlConnHandle);
// Connect to the data source
retCode = SQLConnect(sqlConnHandle, (SQLCHAR*)"YOUR_DSN_NAME", SQL_NTS, (SQLCHAR*)"YOUR_USERNAME", SQL_NTS, (SQLCHAR*)"YOUR_PASSWORD", SQL_NTS);
// Allocate statement handle
retCode = SQLAllocHandle(SQL_HANDLE_STMT, sqlConnHandle, &sqlStmtHandle);
// Get column names
string query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" + tableName + "'";
retCode = SQLExecDirect(sqlStmtHandle, (SQLCHAR*)query.c_str(), SQL_NTS);
// Fetch column names
SQLCHAR colName[256];
while (SQLFetch(sqlStmtHandle) == SQL_SUCCESS) {
SQLGetData(sqlStmtHandle, 1, SQL_C_CHAR, colName, 256, NULL);
cout << colName << endl;
}
// Clean up
SQLFreeHandle(SQL_HANDLE_STMT, sqlStmtHandle);
SQLDisconnect(sqlConnHandle);
SQLFreeHandle(SQL_HANDLE_DBC, sqlConnHandle);
SQLFreeHandle(SQL_HANDLE_ENV, sqlEnvHandle);
return 0;
}
```
请将 "YOUR_DSN_NAME"、"YOUR_USERNAME" 和 "YOUR_PASSWORD" 替换为你的 SQL Server 连接信息。
阅读全文