本文實(shí)例講述了java實(shí)現(xiàn)將結(jié)果集封裝到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); //將結(jié)果集封裝到List中 List list = new ArrayList(); while (rs.next()){ // 可以根據(jù)列名稱也可以根據(jù)列索引 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); //將對(duì)象存放到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 ; } } |
希望本文所述對(duì)大家java程序設(shè)計(jì)有所幫助。