这篇文章主要介绍怎样通过JDBC Statement查询结果集。
通过调用s
tatement.executeQuery()方法来执行查询,语法如下:
- Statement stmt= conn.createStatement();
-
// execute create SQL stetement
-
ResultSet rs = stmt.executeQuery(sql);
代码如下:
- private static void selectRecords() throws SQLException{
-
Connection conn = null;
-
Statement stmt = null;
-
-
String sql = "SELECT id,username,password FROM t_user";
-
try{
-
conn = getDBConnection();
-
stmt = conn.createStatement();
-
-
System.out.println(sql);
-
-
//execute select SQL statement
-
-
ResultSet rs = stmt.executeQuery(sql);
-
while(rs.next()){
-
int id = rs.getInt("id");
-
String username = rs.getString("username");
-
System.out.println("id: "+ id);
-
System.out.println("username: "+ username);
-
}
-
}catch(SQLException e){
-
System.out.println(e.getMessage());
-
}finally{
-
if(stmt!=null){
-
stmt.close();
-
}
-
if(conn!=null){
-
conn.close();
-
}
-
}
-
}
运行结果:
SELECT id,username,password FROM t_user
id: 1
username: HenryPoter
id: 2
username: Dendi
阅读(1103) | 评论(0) | 转发(0) |