views:

383

answers:

1

I have a funny requirement.

We need to have a command-line interaction in a Java Stored Procedure. In spite of granting appropriate permissions using the dbms_java.grant_permission commands, I am encountering java.io.IOException, where I read from System.in using java.io.InputStreamReader.

Where is the problem?

The Java Source is here:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.SQLException;


import oracle.jdbc.driver.OracleDriver;

public class ExecuteInteractiveBatch {

    public static void aFunction() {

        Connection connection = null;
        try {
            int rowFetched = 0;

            connection = new OracleDriver().defaultConnection();

            Statement stmt = connection.createStatement();

            ResultSet rs = stmt.executeQuery("SELECT count(1) cnt from sometable where c = 2");

            int count = 0;
            if (rs.next()) {
                count = rs.getInt(1);
            }
            rs.close();
            stmt.close();
            rs = null;
            stmt = null;
            if (count == 1) {
                System.out.println("Do you want to continue?");
                BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
                String response = reader.readLine();
                if ("Y".equalsIgnoreCase(response)) {
                    stmt = connection.createStatement();
                    int rowsAffected = stmt.executeUpdate("DELETE from sometable where c=2");
                    System.out.println("" + rowsAffected + " row(s) deleted");
                    stmt.close();
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (SQLException ex) {
            ex.printStackTrace();
        } finally {

            try {
                if (connection != null || !connection.isClosed()) {
                    connection.close();
       }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }
}
+5  A: 

You can't perform I/O to the console from within Oracle... not in java, not in PL/SQL, nowhere. Oracle is running in a separate process from the user, quite likely even a different computer, and java stored procedures are being run in that process. You will need some java code running on the client system to perform console I/O.

DCookie