JDBC連接資料庫使用組態檔實作連接查詢功能
JDBC編程六步
- 注冊驅動
- 獲取連接物件(最后要關閉資源)
- 獲取資料庫操作物件,專門執行相應的sql陳述句的物件
- 執行SQL陳述句
- 處理查詢結果集(DQL有這一步,DML陳述句不需要)
- 關閉資源
測驗
組態檔
-
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/mybase user=root password=3333 sql=select empno,ename,sal from emp
執行此查詢陳述句輸出應為
-
select empno,ename,sal from emp; +-------+--------+---------+ | empno | ename | sal | +-------+--------+---------+ | 7369 | SMITH | 800.00 | | 7499 | ALLEN | 1600.00 | | 7521 | WARD | 1250.00 | | 7566 | JONES | 2975.00 | | 7654 | MARTIN | 1250.00 | | 7698 | BLAKE | 2850.00 | | 7782 | CLARK | 2450.00 | | 7788 | SCOTT | 3000.00 | | 7839 | KING | 5000.00 | | 7844 | TURNER | 1500.00 | | 7876 | ADAMS | 1100.00 | | 7900 | JAMES | 950.00 | | 7902 | FORD | 3000.00 | | 7934 | MILLER | 1300.00 | +-------+--------+---------+
測驗程式
-
/* 處理查詢結果集 (遍歷結果集) */ import java.sql.*; import java.util.*; public class JDBCTest06{ public static void main(String[] args){ //組態檔 ResourceBundle bundle = ResourceBundle.getBundle("JDBCTest06"); String driver = bundle.getString("driver"); String url = bundle.getString("url"); String user = bundle.getString("user"); String password = bundle.getString("password"); String sql = bundle.getString("sql"); Connection conn = null; Statement stmt = null; //查詢結果集 ResultSet res = null; try { //1、注冊驅動 Class.forName(driver); //2、獲取連接 conn = DriverManager.getConnection(url,user,password); //3、獲取資料庫操作物件 stmt = conn.createStatement(); //4、執行sql陳述句 res = stmt.executeQuery(sql);//專門執行DQL陳述句的方法 //5、處理查詢結果集 while (res.next()){ String empno = res.getString("empno"); //String empno = res.getString(1); String ename = res.getString("ename"); //String ename = res.getString(2); String sal = res.getString("sal"); //String sal = res.getString(3); System.out.println(empno + "," + ename + "," + sal); } }catch(SQLException e){ e.printStackTrace(); }catch(ClassNotFoundException e){ e.printStackTrace(); }finally{ //6、關閉資源 if(res != null){ try{ res.close(); }catch(SQLException e){ e.printStackTrace(); } } if(stmt != null){ try{ stmt.close(); }catch(SQLException e){ e.printStackTrace(); } } if(conn != null){ try{ conn.close(); }catch(SQLException e){ e.printStackTrace(); } } } } }
輸出
-
7369,SMITH,800.00 7499,ALLEN,1600.00 7521,WARD,1250.00 7566,JONES,2975.00 7654,MARTIN,1250.00 7698,BLAKE,2850.00 7782,CLARK,2450.00 7788,SCOTT,3000.00 7839,KING,5000.00 7844,TURNER,1500.00 7876,ADAMS,1100.00 7900,JAMES,950.00 7902,FORD,3000.00 7934,MILLER,1300.00
結論
- 可以看出結果是一致的
- 只需在組態檔中更改相應的查詢陳述句,就能實作連接查詢
總結
- JDBC中所有下標從1開始,不是從零開始
- 處理結果集的getxxx()方法,傳入的下標從1開始
- 也可以出入查詢表的欄位名,這樣程式更具有健壯性
- 可以回傳多種型別的值
- 當要對回傳的表進行運算時,可以回傳指定型別的資料,并對其進行接收
以上若有錯誤,歡迎批評指正!
本人是正在自學java的小白,剛剛建立了個人博客,歡迎光顧!
網住:我的個人博客歡迎點擊
https://equinoxes.gitee.io/
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/250738.html
標籤:其他
