|
![]() |
名片设计 CorelDRAW Illustrator AuotoCAD Painter 其他软件 Photoshop Fireworks Flash |
|
// 本例展示怎样写用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(); } } } 返回类别: 教程 上一教程: JSP应用的安全问题 下一教程: 标签库完成复杂的后台处理功能的JSP示例 您可以阅读与"DB2中SQLJ应用示例"相关的教程: · JavaBean调用示例(转) · JAVA:ServletContext应用 · Java动态调用类方式的应用 · 启动WebLogic后,不能进入控制台和应用的问题 · JAVA应用技巧-JAVA中的发声提示 |
![]() ![]() |
快精灵印艺坊 版权所有 |
首页![]() ![]() ![]() ![]() ![]() ![]() ![]() |