我有一个方法,其返回类型是客户,这是一个pojo。当我从数据库中获得所需customerId
时,我希望返回客户对象以及customerId
的相应数据。这意味着它有客户名称,地址等。如何进行此操作?
public class Customer verifyCustomerId(cutomerId){
statement = connection.createStatement();
resultSet = statement.executeQuery("select customerid from customer");
while (resultSet.next()) {
if (cutomerId == resultSet.getInt(1)) {
// return data corresponding to this id in the form of object of pojo customer
}
}
return null;
}
答案 0 :(得分:3)
您的SQL语句需要选择要从数据库中返回的数据。您当前的语句将返回customer表中所有行的customerId。
将您的陈述更改为:
PreparedStatement ps = con.prepareStatement("select name from customer where customerId = ?");
ps.setInt(1, cutomerId);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
// use ResultSet to populate Customer pojo
}
我在此处从客户表中选择了名称,但假设存在此列。修改它以选择所需的列。
这是关于PreparedStatements的教程: http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
以下是使用它们的原因: How does a PreparedStatement avoid or prevent SQL injection?
答案 1 :(得分:3)
您可以创建一个Customer
对象,并在其中设置您的属性:
Customer custemer;
if (resultSet.next()) {
customer = new Customer(resultSet.getInt("customerid"));
}
return custemer;
如果您想要获得一个结果而不需要使用while(..)
,则可以改为if
而query
应该有条件"select customerid from customer where ..."
因为您的查询可以获得多个结果,如果您想获得一个List,您可以使用while
这样:
List<Customer> listCustemer = new ArrayList<>();
while (resultSet.next()) {
listCustemer.add(new Customer(resultSet.getInt("customerid")));
}
return listCustemer;
修改强>
您可以更改构造函数并设置您想要的字段,例如姓名,地址和......,如下所示:Customer(int id, String name, String address, ...)
所以你可以使用这个构造函数来创建一个新的Object,如下所示:
listCustemer.add(new Customer(resultSet.getInt("customerid"),
resultSet.getString("name"), resultSet.getString("address"), ...));
答案 2 :(得分:1)
我没有看到任何阻止您获取这些详细信息的内容,您需要做的是编辑您尝试从数据库中获取的QUERY。
public class Customer verifyCustomerId(cutomerId){
statement = connection.createStatement();
CustomerPoJo customer;
resultSet = statement.executeQuery("select * from customer");
while (resultSet.next()) {
if (cutomerId == resultSet.getInt(1)) {
// Fill in the details accordingly
String customername = resultSet.getString(2);
String customeraddress = resultSet.getString(3);
...
customer = new CustomerPoJo();
customer.setCustomerId(customerId);
customer.setCustomerName(customername);
customer.setCustomerAddress(customeraddress);
...
}
}
// Instead send your customer object
return customer;
}