调用SQLDirverConnect远程连接oracle的C代码
时间: 2024-05-12 19:20:24 浏览: 64
C#连接远程Oracle数据库源码
4星 · 用户满意度95%
以下是一个使用SQLDriverConnect远程连接Oracle的C代码示例:
```c
#include <stdio.h>
#include <sql.h>
#include <sqlext.h>
int main() {
SQLHENV env;
SQLHDBC dbc;
SQLHSTMT stmt;
SQLRETURN ret;
SQLCHAR* conn_str = (SQLCHAR*)"DRIVER={Oracle ODBC Driver};SERVER=your_server_address;PORT=1521;UID=your_username;PWD=your_password;DBQ=your_database_name;";
// Allocate an environment handle
ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env);
if (ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO) {
printf("Failed to allocate environment handle\n");
return -1;
}
// Set the ODBC version environment attribute
ret = SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0);
if (ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO) {
printf("Failed to set environment attribute\n");
return -1;
}
// Allocate a connection handle
ret = SQLAllocHandle(SQL_HANDLE_DBC, env, &dbc);
if (ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO) {
printf("Failed to allocate connection handle\n");
return -1;
}
// Connect to the database
ret = SQLDriverConnect(dbc, NULL, conn_str, SQL_NTS, NULL, 0, NULL, SQL_DRIVER_COMPLETE);
if (ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO) {
printf("Failed to connect to database\n");
return -1;
}
// Allocate a statement handle
ret = SQLAllocHandle(SQL_HANDLE_STMT, dbc, &stmt);
if (ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO) {
printf("Failed to allocate statement handle\n");
return -1;
}
// Execute a query
ret = SQLExecDirect(stmt, (SQLCHAR*)"SELECT * FROM your_table", SQL_NTS);
if (ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO) {
printf("Failed to execute query\n");
return -1;
}
// Fetch results
SQLLEN id, name_len;
SQLCHAR name[256];
while (SQLFetch(stmt) == SQL_SUCCESS) {
SQLGetData(stmt, 1, SQL_C_LONG, &id, 0, NULL);
SQLGetData(stmt, 2, SQL_C_CHAR, name, sizeof(name), &name_len);
printf("id = %ld, name = %.*s\n", id, name_len, name);
}
// Clean up
SQLFreeHandle(SQL_HANDLE_STMT, stmt);
SQLDisconnect(dbc);
SQLFreeHandle(SQL_HANDLE_DBC, dbc);
SQLFreeHandle(SQL_HANDLE_ENV, env);
return 0;
}
```
在此示例中,我们首先分配了一个环境句柄,并设置了ODBC版本环境属性。接下来,我们分配了一个连接句柄,并使用SQLDriverConnect函数连接到Oracle数据库。然后,我们分配了一个语句句柄,并使用SQLExecDirect函数执行一个查询。最后,我们使用SQLGetData函数检索查询结果,并清理句柄。请注意,您需要根据您自己的情况替换连接字符串中的占位符。
阅读全文