如何让 Java 方法返回多个值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1736061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I have a Java method return multiple values?
提问by TheQuizitor
I was just wondering whether there's a way to make a Java method return multiple values.
我只是想知道是否有办法让 Java 方法返回多个值。
I'm creating an application that uses the jdbc library to work with a database. I can successfully enter values into the database but I need a way to return them, and this is where I'm a bit stuck. I creating a form into which the user enters a specific value (an ID number) which is then passed to by Database class which carries out my database work.
我正在创建一个使用 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.
The getCust() method in my Database class creates the following query:
我的 Database 类中的 getCust() 方法创建以下查询:
ResultSet Customer = stat.executeQuery("SELECT * FROM Persons WHERE Cust_ID=C_ID");
I need a way to return the results that are stored in Customer back. Any ideas?
我需要一种方法来返回存储在 Customer 中的结果。有任何想法吗?
回答by Tinister
Why not just return Customer, or create a small class with all the values you want returned in it and return that class?
为什么不直接返回 Customer,或者创建一个包含您想要在其中返回的所有值的小类并返回该类?
回答by saleemshafi
You can't exactly return multiple values from a method in Java, but you can always return a container object that holds several values. In your case, the easiest thing to do would be to return the ResultSet, Customer.
在 Java 中,您不能完全从一个方法返回多个值,但您始终可以返回一个包含多个值的容器对象。在您的情况下,最简单的方法是返回 ResultSet、Customer。
If you're concerned about exposing your data layer to your UI, you can copy the data from the ResultSet into a structure that is less specific to the database, either a List of Maps, or perhaps a List of Customer objects, where Custom is a new class that represents your business entity.
如果您担心将数据层暴露给您的 UI,您可以将数据从 ResultSet 复制到一个不太特定于数据库的结构中,要么是地图列表,要么是客户对象列表,其中 Custom 是代表您的业务实体的新类。
回答by Christian
Each customer could be accompanied with a little interface that describes a method that takes multiple arguments. You then pass in the object that implements this interface to have the result delivered to it.
每个客户都可以附带一个小接口,该接口描述了一个接受多个参数的方法。然后传入实现此接口的对象以将结果传递给它。
The object that implement it can of course be the same as the method calling getCustomer
belongs to, so it just passes a reference to 'this' and assign the arguments to fields that you can expect to have been set when it all returns.
实现它的对象当然可以与调用getCustomer
所属的方法相同,因此它只是传递对“this”的引用,并将参数分配给您可以期望在它全部返回时已设置的字段。
回答by ewg
Consider using an object/relational mapping library. It will handle the details of packaging the multiple data values you need to return from the JDBC ResultSet into a single Java bean object.
考虑使用对象/关系映射库。它将处理将需要从 JDBC ResultSet 返回的多个数据值打包到单个 Java bean 对象中的细节。
Which one to pick is another discussion. A lot of smart people use Hibernate. The Java platform includes JPA. Using one off the shelf will save you from inventing your own, which is what devising your own combination of objects and collections would end up being.
选择哪一个是另一个讨论。许多聪明人使用Hibernate。Java 平台包括JPA。使用现成的可以避免你自己发明,这就是设计你自己的对象和集合的组合最终会成为什么。
回答by BalusC
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
.
所以您的实际问题是您不知道如何在 SQL 查询中设置值/参数?唯一正确的方法是使用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 Injectionrisks. Further it's also faster than a Statement
because it's precompiled.
它不仅简化了设置Java对象(String
,Long
,Integer
,Date
,InputStream
等),在SQL查询,但大多数importantingly它将使你免受SQL注入风险。此外,它也比 a 更快,Statement
因为它是预编译的。
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:
至于你的代码逻辑,你应该始终在finally
块中以相反的顺序关闭数据库资源,以避免在异常情况下资源泄漏。以下是如何获得Customer
正确的 JDBC 方式的基本示例:
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 tutorialuseful to get more insights and examples.
您可能会发现本教程有助于获得更多见解和示例。
回答by Fortyrunner
In addition to using Hibernate - take a look at Spring. It supports connection pooling etc and allows you to abstract the JDBC away from your code completely.
除了使用 Hibernate - 看看 Spring。它支持连接池等,并允许您从代码中完全抽象出 JDBC。
It will either return you a List of Maps or a List of your custom type (depending on how you call it).
它将返回地图列表或自定义类型列表(取决于您如何称呼它)。