【问题标题】:Fixing error for invalid identifier修复无效标识符的错误
【发布时间】:2017-04-13 07:22:36
【问题描述】:

我正在创建一个包,然后在其中创建一个存储过程。包装及流程如下:

create or replace package test_system is
    type ref_cursor is ref cursor;
procedure demo_show_students(p_gpa IN STUDENTS.gpa%TYPE,p_ref_cursor  OUT ref_cursor );
end test_system;
/

create or replace package body test_system is
procedure demo_show_students(p_gpa IN STUDENTS.gpa%TYPE,p_ref_cursor   OUT ref_cursor )
is
v_sql_str varchar2(4000);
begin
v_sql_str:='select sid,firstname,lastname,status,gpa,email from students where gpa = p_gpa';
open p_ref_cursor for v_sql_str;
end demo_show_students;
end test_system;

以下是 java 代码,即用于链接两者的 pl/SQL 代码,但它给了我一个问题:

import java.sql.*;

import oracle.jdbc.OracleTypes;

public class ShowStudents {

public void showStudents() {

    try {

        // Connection to Oracle server
        OracleDataSource ds = new oracle.jdbc.pool.OracleDataSource();
        ds.setURL("jdbc:oracle:thin:@localhost:1521:xe");
        Connection conn = ds.getConnection("*****", "*****");

        String val = '4'+"";
        CallableStatement cs = conn.prepareCall("{call        
        test_system.demo_show_students(?,?)}");
        cs.setString(1, val);

        cs.registerOutParameter(2, OracleTypes.CURSOR);
        cs.execute();
        ResultSet rs = (ResultSet)cs.getObject(2);

        while (rs.next()) {
            System.out.println(rs.getString(1) + "\t" +
                rs.getString(2) + "\t" + rs.getString(3) + 
                rs.getString(4) + 
                "\t" + rs.getDouble(5) + "\t" +
                rs.getString(6));
        }


        cs.close();

    } catch (SQLException ex) {
        System.out.println("\n*** SQLException caught ***\n");
        ex.printStackTrace();
    } catch (Exception e) {
        System.out.println("\n*** other Exception caught ***\n");
    }
}
}



Exception : 

*** SQLException caught ***
ORA-00904: "P_GPA": invalid identifier
ORA-06512: at "PROJECT2.TEST_SYSTEM", line 7
ORA-06512: at line 1

谁能告诉我如何解决这个错误。

【问题讨论】:

    标签: java sql oracle stored-procedures plsql


    【解决方案1】:

    oracle 无法识别变量p_gpa。您可以通过两种方式做到这一点:

    1) 放置一个占位符

      v_sql_str:='select sid,firstname,lastname,status,gpa,email from students where gpa = :p_gpa';
    
      open p_ref_cursor for v_sql_str using p_gpa;
    

    2) 直接将查询写成:

    open p_ref_cursor for   
    select sid,firstname,lastname,status,gpa,email 
    from students where gpa = p_gpa;
    

    【讨论】:

    • @Akshay Xing 的两个解决方案都是正确的,但是首选的解决方案是静态 sql 版本(第二种解决方案),因为 a) 不需要使用动态 sql b) 动态 sql 只能在运行时解析,而不是编译时解析。这意味着,如果您的 sql 语句中有错误,则在您真正运行它之前您不会知道它。另外,如果对象被删除,包不会失效,也不会出现在 user_dependencies 等中。如果可以的话,坚持使用静态 SQL,如果真的必须,只回退到动态 sql。跨度>
    猜你喜欢
    • 1970-01-01
    • 2016-08-19
    • 2014-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多