// 本例展示怎样写用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(); } } }