本书中的源代码是以JBuilder工程形式组织的
源代码在线查看: example2.java
package jdbcexample; import java.sql.*; import javax.naming.*; import javax.sql.*; import java.util.Properties; import javax.rmi.PortableRemoteObject; public class Example2 { public static void main(String[] args) { DataSource ds = null; Context ctx = null; Connection myConn = null; try { ctx = getInitialContext(); ds = (javax.sql.DataSource) ctx.lookup("myDataSource"); } catch (Exception E) { System.out.println("Init Error: " + E); } Statement myStatement=null; ResultSet myResultSet=null; try { myConn = ds.getConnection(); myStatement = myConn.createStatement(); myResultSet = myStatement.executeQuery( "SELECT * from employee" ); for(int j=1;j { System.out.print(myResultSet.getMetaData().getColumnName(j)+"\t"); } System.out.println(); while(myResultSet.next()) { for(int j=1;j { System.out.print(myResultSet.getObject(j)+"\t"); } System.out.println(); } myResultSet.close(); } catch (SQLException e) { System.out.println("Error code = " + e.getErrorCode()); System.out.println("Error message = " + e.getMessage()); } finally { try { if (myStatement != null) { myStatement.close(); } if (myConn != null) { myConn.close(); } } catch (SQLException e) { System.out.println("Error code = " + e.getErrorCode()); System.out.println("Error message = " + e.getMessage()); } } } private static Context getInitialContext() throws Exception { String url = "t3://localhost:7001"; String user = "system"; String password = "security"; Properties properties = null; try { properties = new Properties(); properties.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory"); properties.put(Context.PROVIDER_URL, url); if (user != null) { properties.put(Context.SECURITY_PRINCIPAL, user); properties.put(Context.SECURITY_CREDENTIALS, password == null ? "" : password); } return new InitialContext(properties); } catch(Exception e) { throw e; } } }