简体   繁体   中英

How to execute this Oracle statement on JDBC

I have trouble executing the following using a JDBC prepared statement:

CREATE OR REPLACE TRIGGER Time_trg BEFORE INSERT ON Time FOR EACH ROW 
BEGIN 
  SELECT Time_seq.NEXTVAL INTO :new.id FROM dual; 
END;

The code:

try {
   PreparedStatement statement = connection.prepareStatement( sql );
   preparedStatement.executeUpdate();
} finally {
   statement.close();
}

I'm getting this error:

java.sql.SQLException: Missing IN or OUT parameter at index:: 1

I'm working on a database agnostic solution so I need something that is portable. So what is oracle's problem?

There is no need to write our own stored procedure to do this. Oracle provides a built-in stored procedure we can use: DBMS_UTILITY.EXEC_DDL_STATEMENT :

 DBMS_UTILITY.EXEC_DDL_STATEMENT('create table t1 (id number)');

In fact this is safer than the workaround procedure suggested in the accepted answer as it doesn't allow the execution of DML and so is protected against SQL injection

Use oracle.jdbc.OraclePreparedStatement

OraclePreparedStatement statement = (OraclePreparedStatement)connection.prepareStatement( sql );

As this is much specific to Oracle, regular PrepareStatement doesn't help. Oracle provides a wrapper for the same, with additional functionalities as well.

Similarly, Oracle provides OracleCallableStatement similar to CallableStatement

WorkAround: (When PreparedStatement has to be used - Risk of being misused

 CREATE PROCEDURE EXECUTE_MY_DDL(INSTRING VARCHAR2)
 AS
 BEGIN
    EXECUTE IMMEDIATE INSTRING;
 END;

Reference JavaDoc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM