java实现将结果集封装到List中的方法

时间:2022-05-07 10:21:56

本文实例讲述了java实现将结果集封装到List中的方法。分享给大家供大家参考,具体如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class TestResultSet {
  public static List query(){
    Connection conn = new ConnectionUtil().openConnection();
    try {
      Statement stmt = conn.createStatement();
      String sql = "select id,name,email from customertbl";
      ResultSet rs = stmt.executeQuery(sql);
      //将结果集封装到List中
      List list = new ArrayList();
      while(rs.next()){
        // 可以根据列名称也可以根据列索引
        int id = rs.getInt(1);
        String name = rs.getString("name");
        String email = rs.getString("email");
        System.out.println(id+":"+name+":"+email);
        Customer c = new Customer();
        c.setId(id);
        c.setName(name);
        c.setEmail(email);
        //将对象存放到list容器中
        list.add(c);
      }
      return list;
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }finally{
      try {
        conn.close();
      } catch (SQLException e) {
        conn = null;
        e.printStackTrace();
      }
    }
    return null;
  }
}

希望本文所述对大家java程序设计有所帮助。