DB2中SQLJ應用示例 - 中國WEB開發者網絡 (http://www.webasp.net) -- 技術教程 (http://www.webasp.net/article/) --- DB2中SQLJ應用示例 (http://www.webasp.net/article/18/17070.htm) |
| -- 作者:未知 -- 發佈日期: 2005-03-18 |
| // 本例展示怎樣寫用JDBC應用驅動程序存取DB2數據庫的SQLJ應用。
// 其中bank為DB2中的數據庫,customer為bank中的表 import java.sql.*; import sqlj.runtime.*; import sqlj.runtime.ref.*; #sql iterator App_Cursor1 (String customer_id, String customer_name) ; #sql iterator App_Cursor2 (String) ; class App { static { try { // 用 DriverManager 註冊驅動程序 Class.forName("COM.ibm.db2.jdbc.app.DB2Driver").newInstance(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String argv[]) { try { App_Cursor1 cursor1; App_Cursor2 cursor2; String str1 = null; String str2 = null; int count1; Connection con = null; // URL的格式為:jdbc:db2:數據庫名 String url = "jdbc:db2:bank"; DefaultContext ctx = DefaultContext.getDefaultContext(); if (ctx == null) { try { if (argv.length == 0) { // 用默認的用戶名和口令連接 con = DriverManager.getConnection(url); } else if (argv.length == 2) { String userid = argv[0]; String passwd = argv[1]; // 用用戶提供的用戶名和口令連接 con = DriverManager.getConnection(url, userid, passwd); } else { System.out.println(" 用法: java SqljApp [用戶名 口令] "); System.exit(0); } con.setAutoCommit(false); ctx = new DefaultContext(con); } catch (SQLException e) { System.out.println("錯誤: 不能得到默認內容"); System.err.println(e) ; System.exit(1); } DefaultContext.setDefaultContext(ctx); } // 從數據庫提取數據 System.out.println("從數據庫提取一些數據..."); #sql cursor1 = { SELECT customer_id, customer_name from customer }; // 顯示結果集 // cursor1.next() 當無更多的行時返回 false System.out.println("得到的結果:"); while (cursor1.next()) { str1 = cursor1.customer_id(); str2 = cursor1.customer_name(); System.out.print (" 客戶編號= " + str1); System.out.print (" 客戶姓名= " + str2); System.out.print (" "); } cursor1.close(); // 從數據庫中獲取客戶數 System.out.println(" 獲取客戶表的行數..."); #sql { SELECT count(*) into :count1 from customer }; System.out.println ("客戶表中有 " + count1 + " 行."); // 更新數據 str1 = " 1"; System.out.println(" 更新數據... "); #sql { UPDATE customer set customer_name = ´黃亮輝´ where customer_id = :str1 }; // 從數據庫中提取更新數據 System.out.println(" 從數據庫中提取更新數據..."); #sql cursor2 = { SELECT customer_name from customer where customer_id = :str1 }; // 顯示結果集 // cursor2.next() 當無更多行時返回 false System.out.println("得到的結果:"); while (true) { #sql { FETCH :cursor2 INTO :str2 }; if (cursor2.endFetch()) break; System.out.print (" 客戶編號= " + str1); System.out.print (" 客戶姓名= " + str2); System.out.print (" "); } cursor2.close(); // 回滾更新 System.out.println(" 回滾更新..."); #sql { ROLLBACK work }; System.out.println("回滾完成."); } catch( Exception e ) { e.printStackTrace(); } } } |
| webasp.net |