从sql查询中提取数据

时间:2010-11-08 09:33:47

标签: java jdbc

如果我有这样的查询:

然后在执行此操作时,我应该从表中写入每个条目以获取输出。像

现在我如何得到我的飞行表的所有条目。我有2列..

4 个答案:

答案 0 :(得分:1)

假设两列都有String/Varchar类型。

List<Flight> flights = new ArrayList<Flight>();
while(rs.next()){
    Flight flight = new Flight();
    flight.setColumn1(rs.getString(1));   // Its better to use column name instead to avoid any unexpected bug
    flight.setColumn2(rs.getString(2));   // Its better to use column name instead to avoid any unexpected bug 
}

P.S。最好在查询中指定要提取的列,即select COL1, COL2,... from....

答案 1 :(得分:1)

了解ResultSet。代码可能如下所示:

while (rs.next())
    {
    String fld1 = rs.getString("column_name1");
    int fld2 = rs.getInt("column_name2");
    ...
    }

答案 2 :(得分:1)

获得ResultSet后,您将不得不以这种方式进行迭代:

PreparedStatement ps = null;
ResultSet rs = null;
List<Flight> flightList = null;

try {
    String Query = "select * FROM flights WHERE flight_no=? ";
    ps = connection.prepareStatement(query);
    ps.setString(1,"CSC585")
    rs = s.executeQuery();

    if (rs != null) {
        flightList = new ArrayList<Flight>();

        while (rs.next()) { //Moves the cursor from 1 to N
            flightList.add(mapResultSet(rs)); //Write your own mapper....
        }
    }
} catch (SQLException e) {

} finally {
    //First close the ResultSet, then the PreparedStatement
    if (rs != null) {
        try {
            rs.close();
            rs = null;
        } catch (SQLException e) {}
    }

    if (ps != null) {
        try {
            ps.close();
            ps = null;
        } catch (SQLException e) {}
    }
}


Flight mapResultSet(ResultSet rs) throws SQLException {
    Flight flight = null;

    if (rs != null) {
        flight = new Flight();

        flight.setFlightNo(rs.getString("flight_no")); //Column Name as per your SQL table
    }

    return flight...
}

请记住:使用PreparedStatement和ResultSet 完成后,关闭ResultSet 首先,然后关闭 PreparedStatement / * 声明 *

答案 3 :(得分:0)

最用户友好(且最不容易出错)的方式可能是使用Spring的JdbcTemplate抽象:

Spring自己的示例代码:

List<Actor> actors = this.jdbcTemplate.query(
        "select first_name, last_name from t_actor",
        new RowMapper<Actor>() {
            public Actor mapRow(ResultSet rs, int rowNum) throws SQLException{
                Actor actor = new Actor();
                actor.setFirstName(rs.getString("first_name"));
                actor.setLastName(rs.getString("last_name"));
                return actor;
            }
        });