c oci oracle

C语言是一种非常常见的编程语言,它的应用场景广泛,包括操作系统、嵌入式设备、网络编程、游戏开发等等。而这些场景中,数据库的应用也非常普遍。因此,许多开发者都需要学习和掌握使用C语言与数据库进行交互的技能。在这个领域,OCI是一个非常重要的接口,并且被广泛使用。

OCI的全称是Oracle Call Interface,它是Oracle公司提供的一种接口,用于C语言与Oracle数据库进行交互。使用OCI可以实现与Oracle数据库的连接、执行SQL语句、获取查询结果等操作。

下面我们来看一个使用OCI连接Oracle数据库并执行查询的示例:

#include#include#includeint main() { OCIEnv *envhp; OCIError *errhp; OCISvcCtx *svchp; OCIStmt *stmthp; OCIDefine *defhp; OCIParam *param; OCIDateTime *datetime; sword status; ub2 col_type; ub2 size; sb2 ind; ub4 len; double result; char *dbname = "testdb"; char *username = "testuser"; char *password = "testpass"; char *sql = "SELECT AVG(salary) FROM employees"; /* 初始化OCI环境 */ status = OCIEnvCreate(&envhp, OCI_THREADED | OCI_OBJECT, NULL, NULL, NULL, NULL, 0, NULL); if (status != OCI_SUCCESS) { printf("初始化OCI环境失败\n"); return EXIT_FAILURE; } /* 分配OCI错误句柄 */ OCIHandleAlloc(envhp, (void**)&errhp, OCI_HTYPE_ERROR, 0, NULL); /* 连接数据库 */ status = OCILogon(envhp, errhp, &svchp, (OraText*)username, strlen(username), (OraText*)password, strlen(password), (OraText*)dbname, strlen(dbname)); if (status != OCI_SUCCESS) { printf("连接数据库失败\n"); return EXIT_FAILURE; } /* 准备SQL语句 */ status = OCIHandleAlloc(envhp, (void**)&stmthp, OCI_HTYPE_STMT, 0, NULL); if (status != OCI_SUCCESS) { printf("分配SQL语句句柄失败\n"); return EXIT_FAILURE; } status = OCIStmtPrepare(stmthp, errhp, (OraText*)sql, strlen(sql), OCI_NTV_SYNTAX, OCI_DEFAULT); if (status != OCI_SUCCESS) { printf("准备SQL语句失败\n"); return EXIT_FAILURE; } /* 执行SQL语句 */ status = OCIStmtExecute(svchp, stmthp, errhp, 1, 0, NULL, NULL, OCI_DEFAULT); if (status != OCI_SUCCESS) { printf("执行SQL语句失败\n"); return EXIT_FAILURE; } /* 获取查询结果 */ status = OCIParamGet(stmthp, OCI_HTYPE_STMT, errhp, (void**)¶m, 1); if (status != OCI_SUCCESS) { printf("获取查询结果失败\n"); return EXIT_FAILURE; } status = OCIAttrGet(param, OCI_DTYPE_PARAM, (void*)&col_type, &len, OCI_ATTR_DATA_TYPE, errhp); if (status != OCI_SUCCESS) { printf("获取查询结果数据类型失败\n"); return EXIT_FAILURE; } size = 255; switch(col_type) { case SQLT_NUM: status = OCIDefineByPos(stmthp, &defhp, errhp, 1, (dvoid*)&result, sizeof(result), SQLT_FLT, (dvoid*)&ind, NULL, NULL, OCI_DEFAULT); if (status != OCI_SUCCESS) { printf("定义结果变量失败\n"); return EXIT_FAILURE; } break; default: printf("查询结果数据类型不支持\n"); return EXIT_FAILURE; } status = OCIStmtFetch2(stmthp, errhp, 1, OCI_DEFAULT, 0, OCI_DEFAULT); if (status != OCI_SUCCESS && status != OCI_NO_DATA) { printf("获取查询结果失败\n"); return EXIT_FAILURE; } printf("查询结果: %lf\n", result); /* 释放OCI资源 */ OCIStmtRelease(stmthp, errhp, NULL, 0, OCI_DEFAULT); OCILogoff(svchp, errhp); OCIHandleFree(errhp, OCI_HTYPE_ERROR); OCIHandleFree(envhp, OCI_HTYPE_ENV); return EXIT_SUCCESS; }