在C++中處理Oracle數據庫異常,你需要使用Oracle Call Interface (OCI)庫
#include<iostream>
#include <oci.h>
#define CHECK_OCI(func, envhp, errhp) \
if ((func) != OCI_SUCCESS) { \
throw OracleException(envhp, errhp); \
}
OracleException
,用于處理Oracle數據庫異常:class OracleException : public std::exception {
public:
OracleException(OCIEnv* envhp, OCIError* errhp) {
OCIErrorGet((dvoid*)errhp, 1, NULL, &errorCode, errorMessage, sizeof(errorMessage), OCI_HTYPE_ERROR);
OCIHandleFree((dvoid*)envhp, OCI_HTYPE_ENV);
OCIHandleFree((dvoid*)errhp, OCI_HTYPE_ERROR);
}
const char* what() const noexcept override {
return errorMessage;
}
int getErrorCode() const {
return errorCode;
}
private:
char errorMessage[512];
int errorCode;
};
int main() {
try {
OCIEnv* envhp = nullptr;
OCIError* errhp = nullptr;
OCISvcCtx* svchp = nullptr;
OCIServer* srvhp = nullptr;
OCISession* usrhp = nullptr;
// 初始化環境句柄
CHECK_OCI(OCIEnvCreate(&envhp, OCI_DEFAULT, 0, 0, 0, 0, 0, 0), envhp, errhp);
// 分配錯誤句柄
CHECK_OCI(OCIHandleAlloc((dvoid*)envhp, (dvoid**)&errhp, OCI_HTYPE_ERROR, 0, 0), envhp, errhp);
// 分配服務器句柄
CHECK_OCI(OCIHandleAlloc((dvoid*)envhp, (dvoid**)&srvhp, OCI_HTYPE_SERVER, 0, 0), envhp, errhp);
// 分配服務上下文句柄
CHECK_OCI(OCIHandleAlloc((dvoid*)envhp, (dvoid**)&svchp, OCI_HTYPE_SVCCTX, 0, 0), envhp, errhp);
// 分配會話句柄
CHECK_OCI(OCIHandleAlloc((dvoid*)envhp, (dvoid**)&usrhp, OCI_HTYPE_SESSION, 0, 0), envhp, errhp);
// 設置用戶名和密碼
CHECK_OCI(OCIAttrSet((dvoid*)usrhp, OCI_HTYPE_SESSION, (dvoid*)"username", (ub4)strlen("username"), OCI_ATTR_USERNAME, errhp), envhp, errhp);
CHECK_OCI(OCIAttrSet((dvoid*)usrhp, OCI_HTYPE_SESSION, (dvoid*)"password", (ub4)strlen("password"), OCI_ATTR_PASSWORD, errhp), envhp, errhp);
// 連接到數據庫
CHECK_OCI(OCIServerAttach(srvhp, errhp, (text*)"//localhost:1521/orcl", (ub4)strlen("//localhost:1521/orcl"), 0), envhp, errhp);
CHECK_OCI(OCIAttrSet((dvoid*)svchp, OCI_HTYPE_SVCCTX, (dvoid*)srvhp, 0, OCI_ATTR_SERVER, errhp), envhp, errhp);
CHECK_OCI(OCISessionBegin(svchp, errhp, usrhp, OCI_CRED_RDBMS, OCI_DEFAULT), envhp, errhp);
CHECK_OCI(OCIAttrSet((dvoid*)svchp, OCI_HTYPE_SVCCTX, (dvoid*)usrhp, 0, OCI_ATTR_SESSION, errhp), envhp, errhp);
// 在此處執行其他數據庫操作...
// 斷開連接
CHECK_OCI(OCISessionEnd(svchp, errhp, usrhp, OCI_DEFAULT), envhp, errhp);
CHECK_OCI(OCIServerDetach(srvhp, errhp, OCI_DEFAULT), envhp, errhp);
// 釋放句柄
OCIHandleFree((dvoid*)usrhp, OCI_HTYPE_SESSION);
OCIHandleFree((dvoid*)svchp, OCI_HTYPE_SVCCTX);
OCIHandleFree((dvoid*)srvhp, OCI_HTYPE_SERVER);
OCIHandleFree((dvoid*)errhp, OCI_HTYPE_ERROR);
OCIHandleFree((dvoid*)envhp, OCI_HTYPE_ENV);
} catch (const OracleException& e) {
std::cerr << "Oracle Error: " << e.what() << " (Error Code: " << e.getErrorCode() << ")"<< std::endl;
return 1;
}
return 0;
}
這樣,當OCI函數調用失敗時,程序將拋出一個OracleException
異常,你可以捕獲該異常并處理錯誤。