C++读取达梦数据库表数据
时间: 2025-05-06 07:24:35 浏览: 42
要在C++中读取达梦数据库(DM Database)的数据,通常会借助ODBC(开放式数据库连接)。这是因为C++本身并不内置对特定数据库的支持,而ODBC作为一种中间件协议,可以帮助你在多种编程语言和众多类型的数据库之间建立通信桥梁。下面将详细介绍具体的步骤。
### 步骤一:准备工作
#### 1. 安装并配置ODBC驱动程序
首先需要确保已经下载并且正确安装了适用于达梦数据库的ODBC驱动程序,并完成了基本配置测试。
#### 2. 设置数据源名称 (DSN)
通过操作系统提供的控制面板或其他管理工具创建一个新的系统 DSN 或用户 DSN,指向你的达梦数据库实例。
### 步骤二:编写C++代码
接下来我们将展示一段简单的示例代码用于演示如何从C++应用程序读取达梦数据库中的表格信息。这里采用了微软的SQL Native Client库作为例子,但如果你选择了不同的驱动,则相应的函数名可能会有所不同,请参阅对应文档。
```cpp
#include <windows.h>
#include <sqltypes.h>
#include <sqlext.h>
#include <iostream>
int main()
{
SQLHENV hEnv = NULL; /* Environment */
SQLHDBC hDbc = NULL; /* Connection handle */
SQLHSTMT hStmt = NULL; /* Statement handle */
RETCODE retcode;
// Allocate environment handle.
if ((retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &hEnv)) != SQL_SUCCESS &&
retcode != SQL_SUCCESS_WITH_INFO) {
std::cerr << "Error allocating environment.\n";
return -1;
}
// Set the ODBC version environment attribute.
if ((retcode = SQLSetEnvAttr(hEnv, SQL_ATTR_ODBC_VERSION, (void *)SQL_OV_ODBC3, 0)) !=
SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) {
std::cerr << "Error setting ODBC version.\n";
goto cleanup_env;
}
// Allocate connection handle and connect to data source.
if ((retcode = SQLAllocHandle(SQL_HANDLE_DBC, hEnv, &hDbc)) != SQL_SUCCESS &&
retcode != SQL_SUCCESS_WITH_INFO) {
std::cerr << "Error allocating connection.\n";
goto cleanup_env;
}
SQLCHAR connStr[] =
"Driver={DM8 ODBC Driver};"
"Server=localhost;"
"Database=testdb;"
"Uid=SYSDBA;"
"Pwd=mypassword;";
// Connect using the connection string defined above.
if ((retcode = SQLConnect(hDbc,
(SQLCHAR*)connStr, SQL_NTS,
(SQLCHAR*)"", 0,
(SQLCHAR*)"", 0))
!= SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) {
SQLCHAR sqlState[6];
SQLINTEGER nativeError;
SQLCHAR messageText[512];
SQLGetDiagRec(SQL_HANDLE_DBC, hDbc, 1, sqlState, &nativeError, messageText, sizeof(messageText), nullptr);
printf("Connection failed: %s\n%s\n", sqlState, messageText);
goto cleanup_dbc;
}
// Allocate statement handle and execute query.
if ((retcode = SQLAllocHandle(SQL_HANDLE_STMT, hDbc, &hStmt)) != SQL_SUCCESS &&
retcode != SQL_SUCCESS_WITH_INFO) {
std::cerr << "Error allocating statement.\n";
goto cleanup_dbc;
}
const char* query = R"(SELECT id,name FROM my_table)";
if ((retcode = SQLExecDirect(hStmt, (SQLCHAR*)query, SQL_NTS))
!= SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) {
std::cerr << "Error executing SELECT.\n";
goto cleanup_stmt;
}
// Fetch rows one at a time in a loop until there are no more rows.
int idValue;
char nameBuffer[1024]; // Adjust buffer size according to your needs.
while ((retcode = SQLFetch(hStmt)) == SQL_SUCCESS ||
retcode == SQL_SUCCESS_WITH_INFO) {
// Get column values by ordinal position or name into variables...
retcode = SQLGetData(hStmt, 1, SQL_C_LONG, &idValue, 0, NULL);
retcode = SQLGetData(hStmt, 2, SQL_C_CHAR, nameBuffer,sizeof(nameBuffer)-1,NULL );
cout << "ID:" << idValue << ", Name:" << nameBuffer << "\n";
}
cleanup_stmt:
// Free resources associated with processing this request.
if (hStmt != NULL)
SQLFreeHandle(SQL_HANDLE_STMT, hStmt);
cleanup_dbc:
// Disconnect from server and free connection handles.
if (hDbc != NULL) {
SQLEndTran(SQL_HANDLE_DBC, hDbc, SQL_ROLLBACK);
SQLDisconnect(hDbc);
SQLFreeHandle(SQL_HANDLE_DBC, hDbc);
}
cleanup_env:
// Release the environment allocated earlier.
if (hEnv != NULL)
SQLFreeHandle(SQL_HANDLE_ENV, hEnv);
return retcode >= SQL_ERROR ? -1 : 0;
}
```
此段代码展示了典型的 C++ 程序使用 ODBC 接口同达梦数据库进行交互的过程。请注意修改连接字符串 (`connStr`) 内容以匹配你自己的数据库设置,并调整查询语句为你希望检索的具体内容。
此外还需要注意的是,这仅是一个基础框架,真实的生产环境中应当添加更多健壮性和安全性措施,例如错误处理、输入验证等等。
---
阅读全文
相关推荐


















