一个将SQL语句嵌入到Java应用程序中的实例
2023-03-31 11:06:55 时间
我们在将SQL语句嵌入应用程序时,必须按以下的两个步骤预编译应用程序并将其与数据库联编,步骤如下:
1.创建源文件,以包含带嵌入式SQL语句的程序。
格式: # SQL{ SQL语句 } 。
2.连接数据库,然后预编译每个源文件。
语法: SQLJ 源文件名。
实例如下:
- import java.sql.*;
- import sqlj.runtime.*;
- import sqlj.runtime.ref.*;
- #sql iterator App_Cursor1 (String empno, String firstnme) ;
- #sql iterator App_Cursor2 (String) ;
- class App
- {
- static
- {
- try
- {
- Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- }
- public static void main(String argv[])
- {
- try
- {
- App_Cursor1 cursor1;
- App_Cursor1 cursor2;
- String str1 = null;
- String str2 = null;
- int count1;
- Connection con = null;
- String url = "jdbc:odbc:tese2";
- DefaultContext ctx = DefaultContext.getDefaultContext();
- if (ctx == null) {
- try {
- if (argv.length == 0) {
- String userid ="tdl";
- String passwd ="user";
- con = DriverManager.getConnection(url, userid, passwd);
- }
- else if (argv.length == 2) {
- // connect with default id/password
- con = DriverManager.getConnection(url);
- }
- else {
- System.out.println("Usage: java App [username password]");
- System.exit(0);
- }
- con.setAutoCommit(false);
- ctx = new DefaultContext(con);
- }
- catch (SQLException e) {
- System.out.println("Error: could not get a default context");
- System.err.println(e) ;
- System.exit(1);
- }
- DefaultContext.setDefaultContext(ctx);
- }
- #sql cursor1 = { SELECT empno, firstnme from db2admin.employee };
- System.out.println("Received results:");
- while (cursor1.next()) {
- str1 = cursor1.empno();
- str2 = cursor1.firstnme();
- System.out.print (" empno= " + str1);
- System.out.print (" firstname= " + str2);
- System.out.print ("");
- }
- cursor1.close();
- #sql cursor2 = { SELECT firstnme from db2admin.employee where empno = :str1 };
- System.out.println("Received results:");
- while (true) {
- #sql { FETCH :cursor2 INTO :str2 };
- if (cursor2.endFetch()) break;
- System.out.print (" empno= " + str1);
- System.out.print (" firstname= " + str2);
- System.out.print ("");
- }
- cursor2.close();
- // rollback the update
- System.out.println("Rollback the update...");
- #sql { ROLLBACK work };
- System.out.println("Rollback done.");
- }
- catch( Exception e )
- {
- e.printStackTrace();
- }
- }
- }
注:本程序采用JDBCODBC桥的方式访问数据库,必须配置ODBC数据源。
关于嵌入式SQL(SQLJ)的知识就介绍到这里了,希望本次的介绍能够给您带来一些收获!
【编辑推荐】
相关文章
- 深入探讨Java中的异常与错误处理
- 研究学习Kotlin的一些方法
- 数据显示Java热度持续下落,日子屈指可数?
- 2017年5月编程语言排行榜:Java与C语言优势正开始缩小
- Java多线程之内置锁与显示锁
- Java线程池的理论与实践
- 白话阿里巴巴Java开发手册(编程规约)
- 关于Java你不知道的十件事
- Java服务化系统线上应急和技术攻关,你必须掌握的Linux命令
- Java实现高斯模糊和图像的空间卷积
- Java阻塞队列实现原理分析
- NPM使用技巧
- Node.js对Java开发者而言是什么?
- Java反射机制应用实践
- 理解RxJava中的Single和Completable
- 2017年你不能错过的Java类库
- 大规模集群下的Hadoop NameNode
- 从源码解密Spark内存管理
- 2017年3月编程语言排行榜:Swift首次进入前十
- JVM热点技术:Java类的加载机制