JDBC查詢指定條件的數據


使用select語句的條件查詢,需要用到where子句。

 1 package qddx.JDBC;
 2 import java.sql.*;
 3 public class QueryById {
 4 
 5     public bbsVo QuerybbsVoById(int id){
 6         bbsVo vo = null;
 7         Connection conn = null;
 8         PreparedStatement pst = null;
 9         ResultSet rs = null;
10         try{
11         conn = JDBC_Connection.getConnection();
12         pst = conn.prepareStatement("select * from article where id=?");
13         pst.setInt(1, id);//設置條件id
14         rs=pst.executeQuery();
15         while(rs.next()){//結果集存在則進行遍歷
16             vo = new bbsVo();
17             vo.setId(rs.getInt("id"));
18             vo.setPid(rs.getInt("pid"));
19             vo.setRootid(rs.getInt("rootid"));
20             vo.setCont(rs.getString("cont"));
21             vo.setPdate(rs.getTimestamp("pdate"));
22             vo.setIsleaf(rs.getInt("isleaf"));
23             vo.setTitle(rs.getString("title"));
24             
25         }
26         }catch(SQLException e){
27             e.printStackTrace();
28         }finally{
29             JDBC_Connection.free(rs, conn, pst);
30         }
31         return vo;
32         
33     }
34     public static void main(String[] args) {
35         // TODO Auto-generated method stub
36         QueryById byid = new QueryById();
37         int id = 3;
38         bbsVo vo = byid.QuerybbsVoById(id);
39         if(vo!=null){
40             System.out.print("id\t");
41             System.out.print("pid\t");
42             System.out.print("rootid\t");
43             System.out.print("title\t\t");
44             System.out.print("cont\t");
45             System.out.print("pdate\t");
46             System.out.print("isleaf\t");
47             System.out.println();
48             System.out.print(vo.getId()+"\t");
49             System.out.print(vo.getPid()+"\t");
50             System.out.print(vo.getRootid()+"\t");
51             System.out.print(vo.getTitle()+"\t");
52             System.out.print(vo.getCont()+"\t");
53             System.out.print(vo.getPdate()+"\t");
54             System.out.print(vo.getIsleaf()+"\t");
55         }else{
56             System.out.println("id為"+id+" 的用戶不存在");
57         }
58     }
59 
60 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM