I’m trying to use the following code to run a PL/SQL statement on my database server.
public class Main {
public static void main(String[] args) {
String jdbcURL = "jdbc:oracle:thin:@172.22.88.9:1521/xavier.i.com";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String user = "bigdb";
String password = "fakepassword";
String result = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
conn = DriverManager.getConnection(jdbcURL, user, password);
result = runStatement(conn,
"{begin ANALYZE TABLE BIGDB.scr_fct_exact_access
ESTIMATE STATISTICS; end}");
} catch (Exception ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
private static String runStatement(Connection con, String statement)
throws Exception {
PreparedStatement cstmt = con.prepareStatement(statement);
cstmt.execute(); // this is line 58
cstmt.close();
return count;
}
}
On running the code, I get the following exception:
java.sql.SQLSyntaxErrorException: ORA-00900: invalid SQL statement
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:440)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:837)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:445)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:191)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:523)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:207)
at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:1010)Time : -1307015416548at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1315)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3576)
at oracle.jdbc.driver.OraclePreparedStatement.execute(OraclePreparedStatement.java:3677)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.execute(OraclePreparedStatementWrapper.java:1374)
at Main.prepareStatement(Main.java:58)
at Main.main(Main.java:29)
What is going wrong, and how can I fix it?
ANALYZE TABLEis a DDL (data definition language) statement. It’s not valid within a BEGIN/END block in PL/SQL. If you wanted to execute it in PL/SQL, you’d need to use EXECUTE IMMEDIATE.To run the statement from JDBC, just create a
Statementinstance and useexecuteUpdate:But a even better idea is to use the
DBMS_STATSpackage to analyze your tables. Then you can use your approach with BEGIN/END.