使用 PHP OCI8 从 Oracle Ref Cursor 获取数据

问题描述 投票:0回答:1

我正在尝试从 oracle pl/sql 函数获取数据,该函数返回 REF 游标。我写了测试函数,只是为了检查它。我正在使用新的 Oracle 19g 和 Windows 中的 WAMP,以及 Oracle 驱动程序。



Function code:    FUNCTION getTestData
    
      RETURN types_package.cursor_type
      
      
 AS
      list_cursor   types_package.cursor_type;
      tmpcnt        INTEGER;
   BEGIN
   
      OPEN list_cursor FOR
           SELECT field1  from test;

      RETURN list_cursor;
      
    end;     

我尝试了很多其他方法,但每次我都会遇到一些错误,例如“无效获取”或“ora-01008”。 我的问题是,这可能吗?或者在 oracle 中使用 OCI8 和引用游标存在一些已知问题? 让标量变量对我来说很有用,但我需要引用游标。从 SELECT 查询获取数据也可以正常工作。

<?php

// Replace these variables with your actual Oracle database credentials
$database = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.202.238)(PORT=1521))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=PDB1)))";
$username = "***";
$password = "*****";

// Attempt to establish a connection
$conn = oci_connect($username, $password, $database);

if ($conn) {
    echo "Connected to Oracle database successfully!";
    oci_close($conn); // Close the connection
} else {
    $error = oci_error(); // Get the error if connection fails
    echo "Failed to connect to Oracle database: " . $error['message'];
}


      // Prepare the SQL statement with the stored function call
    $sql = "BEGIN :result := test_pkg.getTestData(); END;";
      $stmt = oci_parse($conn, $sql);

    // Bind the result parameter as a REF CURSOR
    $result = oci_new_cursor($conn);
    oci_bind_by_name($stmt, ':result', $result, -1, OCI_B_CURSOR);

    // Execute the statement
    oci_execute($stmt);

    // Define the fetch mode for the columns
    oci_define_by_name($result, 'COLUMN_NAME', $columnValue);

    // Fetch the result from the REF CURSOR
    while (oci_fetch($result)) {
        // Access the returned data
        // Example: $value = $columnValue;
    }

    // Close the statement and connection
    oci_free_statement($stmt);
    oci_close($conn); 

php oracle oci8
1个回答
0
投票

您正在执行

$stmt
,它将引用光标返回到
$result
,但随后您必须执行
$result
才能实际执行引用光标本身:

oci_execute($stmt); // gets the ref cursor
oci_execute($result); // executes the ref cursor
© www.soinside.com 2019 - 2024. All rights reserved.