使用其他结果集从DB返回值

时间:2016-04-18 04:12:35

标签: java jdbc prepared-statement resultset postgresql-9.4

如何执行此语句并将其处理为java。是否有可能获得一个返回值,然后是下一个结果集,这是我正在做的选择员工?

我无法在Google上找到准确的方式来执行我想要的操作,因为所有示例都是使用单个SELECT的结果,并且无法使用来自DB的RETURN查找查询。但是根据这个question,可以像.NET那样从DB(java)管理多个结果集。

我正在使用postgresql 9.4,我不想使用存储过程(函数)来做我想做的事。

这是我一直在尝试测试的代码,但我得到一个例外,即“IF”第1行存在语法错误

public Employee getEmployee(Connection con, String code) {
    Employee employee = new Employee();
    try {
        String query = 
                "IF EXISTS(SELECT * FROM employee WHERE code = ?) THEN "
                + "RETURN 1; "
                + "ELSE "
                + "RETURN 2; "
                + "END IF; "
                + "SELECT EmployeeID, FirstName FROM employee where code = ?; ";
        PreparedStatement stmt = con.prepareStatement(query);
        stmt.setString(1, code);
        stmt.setString(2, code);
        boolean hasResults = stmt.execute();
        int returnValue = 0;
        while(hasResults){
            ResultSet rs = stmt.getResultSet();
            returnValue = rs.getInt(1);
            if(returnValue == 1){
                hasResults = stmt.getMoreResults();
                while(hasResults){
                    employee.setId(rs.getInt("EmployeeID"));
                    employee.setFirstName(rs.getString("FirstName"));
                }
            }
        }
        return employee;
    } catch (Exception e) {
        System.out.println(e.getMessage());
        return null;
    }

1 个答案:

答案 0 :(得分:0)

你过于复杂(除了SQL中没有if这一事实)。

只需运行select,如果没有这样的员工,你将得到一个空的结果集:

public Employee getEmployee(Connection con, String code) {
    Employee employee = new Employee();
    try {
        String query = "SELECT EmployeeID, FirstName FROM employee where code = ?";
        PreparedStatement stmt = con.prepareStatement(query);
        stmt.setString(1, code);
        ResultSet rs = stmt.executeQuery();
        if (rs.next()){
            employee.setId(rs.getInt("EmployeeID"));
            employee.setFirstName(rs.getString("FirstName"));
        }
        return employee;
    } catch (Exception e) {
        System.out.println(e.getMessage());
        return null;
    }
}

您还可能希望在Employee内移动if (rs.next())实例的创建,这样如果没有员工存在,您的方法将返回null。即使没有

,上面的代码也会返回Employee

您还应该从查询字符串中删除;。虽然Postgres驱动程序很乐意运行以;终止的语句,但这不符合JDBC,而其他驱动程序(或DBMS)可能拒绝运行它。