java之jdbc_採用Statement查詢所有數據

動力節點筆記java

  
  
  
  
  1. import java.sql.*;  
  2. //採用Statement查詢所有數據  
  3. public class QueryTest03 {  
  4.     public static void main(String[] args) {  
  5.         Connection conn = null;  
  6.         Statement stmt = null;  
  7.         ResultSet rs = null;  
  8.         try {  
  9.             //第一步,加載數據庫驅動,不一樣的數據庫驅動程序不同  
  10.             Class.forName("oracle.jdbc.driver.OracleDriver");  
  11.             //第二部,獲得數據庫鏈接  
  12.             String dburl = "jdbc:oracle:thin:@localhost:1521:orcl";  
  13.             //String dburl = "jdbc:oracle:thin:@192.168.21.1:1521:orcl";  
  14.             //String dburl = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";  
  15.             String userName = "system";  
  16.             String password = "wanwan";  
  17.             conn = DriverManager.getConnection(dburl, userName, password);  
  18.             //System.out.println(conn);  
  19.               
  20.             //第三步,建立Statement,執行SQL語句  
  21.             stmt = conn.createStatement();  
  22.             //第四部,取得結果集  
  23.             rs = stmt.executeQuery("select * from tb_student");  
  24.             while (rs.next()) {  
  25.                 int id = rs.getInt("id");  
  26.                 String name = rs.getString("name");  
  27.                 System.out.println(id + " , " + name);  
  28.             }   
  29.               
  30.             System.out.println("============================");  
  31.             //能夠採用索引號取得字段的值,索引從1開始,  
  32.             //儘可能不要使用索引號的方式,由於不明確  
  33.             rs = stmt.executeQuery("select * from tb_student");  
  34.             while (rs.next()) {  
  35.                 int id = rs.getInt(1);  
  36.                 String name = rs.getString(2);  
  37.                 System.out.println(id + "," + name);  
  38.             }  
  39.               
  40.         } catch (ClassNotFoundException e) {  
  41.             e.printStackTrace();  
  42.         } catch (SQLException e) {  
  43.             e.printStackTrace();  
  44.         } finally {  
  45.             //注意關閉原則:從裏到外  
  46.               
  47.               
  48.             try {  
  49.                 if (rs != null) {  
  50.                 rs.close();   
  51.                 }  
  52.                 if (stmt != null) {  
  53.                     stmt.close();     
  54.                 }  
  55.                     if (conn != null) {  
  56.                     conn.close();  
  57.                     }  
  58.             } catch(SQLException e) {  
  59.                           
  60.             }  
  61.               
  62.         }  
  63.     }     
  64. }  
相關文章
相關標籤/搜索