Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2536738
  • 博文数量: 245
  • 博客积分: 4125
  • 博客等级: 上校
  • 技术积分: 3113
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-25 23:56
文章分类

全部博文(245)

文章存档

2015年(2)

2014年(26)

2013年(41)

2012年(40)

2011年(134)

2010年(2)

分类: Java

2011-12-27 16:01:02

这篇文章主要介绍怎样通过JDBC Statement查询结果集。
通过调用statement.executeQuery()方法来执行查询,语法如下:
  1. Statement stmt= conn.createStatement();
  2. // execute create SQL stetement
  3. ResultSet rs = stmt.executeQuery(sql);
代码如下:

  1. private static void selectRecords() throws SQLException{
  2.         Connection conn = null;
  3.         Statement stmt = null;
  4.         
  5.         String sql = "SELECT id,username,password FROM t_user";
  6.         try{
  7.             conn = getDBConnection();
  8.             stmt = conn.createStatement();
  9.             
  10.             System.out.println(sql);
  11.             
  12.             //execute select SQL statement
  13.             
  14.             ResultSet rs = stmt.executeQuery(sql);
  15.             while(rs.next()){
  16.                 int id = rs.getInt("id");
  17.                 String username = rs.getString("username");
  18.              System.out.println("id: "+ id);
  19.              System.out.println("username: "+ username);
  20.             }
  21.         }catch(SQLException e){
  22.             System.out.println(e.getMessage());
  23.         }finally{
  24.             if(stmt!=null){
  25.                 stmt.close();
  26.             }
  27.             if(conn!=null){
  28.                 conn.close();
  29.             }
  30.         }
  31.     }

运行结果:
SELECT id,username,password FROM t_user
id: 1
username: HenryPoter
id: 2
username: Dendi
阅读(1064) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~