我们在将SQL语句嵌入应用程序时,必须按以下的两个步骤预编译应用程序并将其与数据库联编,步骤如下:

1.创建源文件,以包含带嵌入式SQL语句的程序。

格式: # SQL{ SQL语句 } 。

2.连接数据库,然后预编译每个源文件。

语法: SQLJ 源文件名。

实例如下:

    importjava.sql.*; importsqlj.runtime.*; importsqlj.runtime.ref.*; #sqliteratorApp_Cursor1(Stringempno,Stringfirstnme); #sqliteratorApp_Cursor2(String); classApp { static { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance(); } catch(Exceptione) { e.printStackTrace(); } } publicstaticvoidmain(Stringargv[]) { try { App_Cursor1cursor1; App_Cursor1cursor2; Stringstr1=null; Stringstr2=null; intcount1; Connectioncon=null; Stringurl="jdbc:odbc:tese2"; DefaultContextctx=DefaultContext.getDefaultContext(); if(ctx==null){ try{ if(argv.length==0){ Stringuserid="tdl"; Stringpasswd="user"; con=DriverManager.getConnection(url,userid,passwd); } elseif(argv.length==2){ //connectwithdefaultid/password con=DriverManager.getConnection(url); } else{ System.out.println("Usage:javaApp[usernamepassword]"); System.exit(0); } con.setAutoCommit(false); ctx=newDefaultContext(con); } catch(SQLExceptione){ System.out.println("Error:couldnotgetadefaultcontext"); System.err.println(e); System.exit(1); } DefaultContext.setDefaultContext(ctx); } #sqlcursor1={SELECTempno,firstnmefromdb2admin.employee}; System.out.println("Receivedresults:"); while(cursor1.next()){ str1=cursor1.empno(); str2=cursor1.firstnme(); System.out.print("empno="+str1); System.out.print("firstname="+str2); System.out.print(""); } cursor1.close(); #sqlcursor2={SELECTfirstnmefromdb2admin.employeewhereempno=:str1}; System.out.println("Receivedresults:"); while(true){ #sql{FETCH:cursor2INTO:str2}; if(cursor2.endFetch())break; System.out.print("empno="+str1); System.out.print("firstname="+str2); System.out.print(""); } cursor2.close(); //rollbacktheupdate System.out.println("Rollbacktheupdate..."); #sql{ROLLBACKwork}; System.out.println("Rollbackdone."); } catch(Exceptione) { e.printStackTrace(); } } }

注:本程序采用JDBCODBC桥的方式访问数据库,必须配置ODBC数据源。

关于嵌入式SQL(SQLJ)的知识就介绍到这里了,希望本次的介绍能够给您带来一些收获!

【编辑推荐】

    Oracle数据库中Constraint约束的四对属性SQL Server 2005无法连接到本地服务器的解决Linux下重新配置MySQL数据库引擎innodb的过程Navicat MySQL连接Linux下MySQL的问题解决方案SQL Server 2000在Windows7 旗舰版中的安装配置