我們在將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)的知識就介紹到這裡了,希望本次的介紹能夠給您帶來一些收獲!