如何将查询结果传递给另一个方法

时间:2017-06-06 15:39:16

标签: java sql

我在查询

select empname 
from employee 
where empsal > 5000

我有3行(一列有3行),现在我想把它作为字符串数组返回。

然后我想将String数组中的字符串作为单独的字符串

2 个答案:

答案 0 :(得分:1)

更面向对象的方法是循环遍历结果集,但不是在数组中分配字符串,而是创建一个封装您从数据库中检索的数据的对象。您只需将字符串存储在数组中就可以限制自己。使用反映您的业务需求/域的对象。

例如:

import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class Employee {

    private String name;
    private int salary;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }

}

class DataAccessor {

    public List<Employee> getEmployees() {

        List<Employee> employeeList = new ArrayList<Employee>();

        String query = "select empname, empsal from employee where empsal>5000";

        // Create the database connection & statement somehow...
        Statement stmt = createStatement();

        try {
           ResultSet results = stmt.executeQuery(query);

           while (results.next()) {
               Employee employee = new Employee();
               employee.setName(results.getString(1));
               employee.setSalary(results.getInt(2));
               employeeList.add(employee);
           }
        } finally {
           stmt.close();
        }

        return employeeList;
    }

}

答案 1 :(得分:0)

使用ResultSet遍历rs.next(),然后将每行添加到ArrayList<String>。然后你可以通过它们的索引获得“单独的字符串”。

相关问题