我只是想知道是否有办法让Java方法返回多个值。
我正在创建一个使用jdbc库来处理数据库的应用程序。我可以成功地将值输入到数据库中,但我需要一种方法来返回它们,这就是我有点卡住的地方。我创建了一个表单,用户输入一个特定的值(一个ID号),然后由执行我的数据库工作的Database类传递给它。
Database newQuery = new Database();
newQuery.getCust(c_ID); //uses the GetCust method in my class,
//passing it the ID of the customer.
我的Database类中的getCust()方法创建以下查询:
ResultSet Customer = stat.executeQuery("SELECT * FROM Persons WHERE Cust_ID=C_ID");
我需要一种方法来返回存储在Customer中的结果。有什么想法吗?
答案 0 :(得分:7)
为什么不直接返回Customer,或创建一个包含您想要在其中返回的所有值的小类并返回该类?
答案 1 :(得分:7)
您无法从Java中的方法返回多个值,但始终可以返回包含多个值的容器对象。在您的情况下,最简单的方法是返回ResultSet,Customer。
如果您担心将数据层暴露给UI,则可以将ResultSet中的数据复制到不太特定于数据库的结构中,可以是List of Maps,也可以是List of Customer对象,其中Custom是一个代表您的业务实体的新类。
答案 2 :(得分:3)
所以你的实际问题是你不知道如何在SQL查询中设置值/参数?唯一正确的方法是使用PreparedStatement
。
String sql = "select * from Customers where Cust_ID = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setLong(custId);
resultSet = preparedStatement.executeQuery();
它不仅可以在SQL查询中轻松设置Java对象(String
,Long
,Integer
,Date
,InputStream
等等,而且还可以最重要的是,它可以帮助您免除SQL Injection risks。此外,它也比Statement
快,因为它是预编译的。
对于您的代码逻辑,您应始终以finally
块中的相反顺序关闭数据库资源,以避免在出现异常时资源泄漏。以下是如何以正确的JDBC方式获取Customer
的基本示例:
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;
}
您可能会发现this tutorial对获取更多见解和示例非常有用。
答案 3 :(得分:0)
每个客户都可以附带一个描述采用多个参数的方法的小接口。然后传入实现此接口的对象以将结果传递给它。
实现它的对象当然可以与调用getCustomer
所属的方法相同,因此它只是将引用传递给'this'并将参数分配给您可以预期设置的字段当它全部返回时。
答案 4 :(得分:0)
考虑使用对象/关系映射库。它将处理将您需要从JDBC ResultSet返回的多个数据值打包到单个Java bean对象中的详细信息。
选择哪一个是另一个讨论。很多聪明人使用Hibernate。 Java平台包括JPA。使用现成的产品将使您免于发明自己的产品,这就是设计自己的对象和产品组合最终会产生的结果。
答案 5 :(得分:0)
除了使用Hibernate之外 - 看一下Spring。它支持连接池等,并允许您完全从代码中抽象出JDBC。
它会返回一个地图列表或您自定义类型的列表(取决于您如何调用它)。