• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

DB2中SQLJ应用示例

servlet/jsp 搞代码 7年前 (2018-06-18) 196次浏览 已收录 0个评论

// 本例展示怎样写用JDBC应用驱动程序存取DB2数据库的SQLJ应用。
// 其中bank为DB2中的数据库,customer为bank中的表
import java.sql.*;
import sqlj.runtime.*;
import sqlj.runtime.ref.*;

http://www.gaodaima.com/41628.htmlDB2中SQLJ应用示例

#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();
}
}
} 

欢迎大家阅读《DB2中SQLJ应用示例》,跪求各位点评,若觉得好的话请收藏本文,by 搞代码


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:DB2中SQLJ应用示例

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址