从Java调用SQL包过程

时间:2018-06-13 19:14:49

标签: java sql oracle

我有一个oracle SQL过程,我想从我的Java代码中调用,但我无法弄清楚如何做到这一点。我知道我的程序运行正常,因为当我在SQLDeveloper中使用它时,我没有任何问题。当我从我的Java代码调用时,我得到一个SQLSyntaxErrorException:无效的SQL语句。

这是我到目前为止的代码......

private DataSource datasource;

private static final Map<String, String> SQL_KEYS = new HashMap<String, String>();

static {
    SQL_KEYS.put("updatePassword", 
            "EXEC MY_VIEW_SECURITY.CHANGE_PASSWORD(?, ?, ?)");
}

public void updatePassword(String username, String old_password, String new_password) throws SQLException {
    Connection con = null;
    CallableStatement cstmt = null;

    try {
        con = datasource.getConnection();
        cstmt = con.prepareCall(SQL_KEYS.get("updatePassword"));

        cstmt.setString(1, username);
        cstmt.setString(2, old_password);
        cstmt.setString(3, new_password);

        cstmt.executeUpdate();      

    } catch(Exception ex) {
        ex.printStackTrace();
    } finally {
        con.close();
        cstmt.close();
    }
}

我没有正确的Java代码语法的updatePassword字符串,因为它在SQLDeveloper中可以正常工作吗?

我已经尝试在给出SQLSyntaxErrorException的语句中将EXEC切换到CALL:在下级会话中不允许COMMIT。我不确定这是否是正确的方向。

1 个答案:

答案 0 :(得分:0)

EXEC不是SQL command,因此您无法在JDBC中使用它。

run a stored procedure,您需要在准备{call ...}时使用CallableStatement

cstmt = con.prepareCall("{call Y_VIEW_SECURITY.CHANGE_PASSWORD(?, ?, ?)}");
cstmt.setString(1, username);
cstmt.setString(2, old_password);
cstmt.setString(3, new_password);

请注意{}是传递给prepareCall()的字符串的一部分