How can I have a Java method return multiple values?

前端 未结 6 1999
灰色年华
灰色年华 2020-12-21 19:10

I was just wondering whether there\'s a way to make a Java method return multiple values.

I\'m creating an application that uses the jdbc library to work with a data

6条回答
  •  自闭症患者
    2020-12-21 19:32

    So your actual problem is that you didn't know how to set values/parameters in a SQL query? The only right way to do this is using PreparedStatement.

    String sql = "select * from Customers where Cust_ID = ?";
    preparedStatement = connection.prepareStatement(sql);
    preparedStatement.setLong(custId);
    resultSet = preparedStatement.executeQuery();
    

    It not only eases setting Java objects (String, Long, Integer, Date, InputStream and so on) in a SQL query, but most importantingly it will save you from SQL Injection risks. Further it's also faster than a Statement because it's precompiled.

    As to your code logic, you should always close the DB resources in the reverse order in the finally block to avoid resource leaks in case of exceptions. Here's a basic example how to obtain a Customer the right JDBC way:

    public Customer find(Long customerId) throws SQLException {
        String sql = "SELECT id, name, age FROM customer WHERE id = ?";
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        Customer customer = null;
    
        try {
            connection = getConnectionSomehow();
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setLong(custId);
            resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                customer = new Customer();
                customer.setId(resultSet.getLong("id"));
                customer.setName(resultSet.getString("name"));
                customer.setAge(resultSet.getInteger("age"));
            }
        } finally {
            if (resultSet != null) try { resultSet.close(); } catch (SQLException ignore) {}
            if (preparedStatement != null) try { preparedStatement.close(); } catch (SQLException ignore) {}
            if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
        }
    
        return customer;
    } 
    

    You may find this tutorial useful to get more insights and examples.

提交回复
热议问题