值得注意的是: 需要在CLASSPATH中設定好
commons-dbcp-1.2.2.jar; commons-pool-1.4.jar;naming-common.jar一個檔案的路徑
這三個檔案可以直接在Apache的網站上下載, 若裝有Tomcat, 在<Tomcat Path>/common/lib
路徑下也可以找到
import javax.sql.*;
import javax.naming.*;
import java.sql.*;
import java.util.*;
import org.apache.commons.dbcp.*;
public class JNDI_Demo {
public static void main(String[] args) {
try{
BasicDataSource basDS = new BasicDataSource();
basDS.setDriverClassName("com.microsoft.jdbc.sqlserver.SQLServerDriver");//Setting database driver
basDS.setUrl("jdbc:microsoft:sqlserver://localhost:1433;databaseName=pubs;");//Setting JDBC's URL
basDS.setUsername("sa");
basDS.setPassword("");
basDS.setInitialSize(2);//Setting connection-pooling
//Config JNDI
Hashtable hashTab = new Hashtable();
hashTab.put("java.naming.factory.initial","org.apache.naming.java.javaURLContextFactory");
InitialContext ctx=new InitialContext(hashTab);
ctx.bind("JNDI_DS",bdds);//Bind datasource to JNDI
DataSource ds = (DataSource)ctx.lookup("JNDI_DS");//Search datasource in JNDI
Connection con = ds.getConnection();
Statement stmt = con.createStatement();
String strSql = "SELECT AU_ID, PHONE FROM AUTHORS";
ResultSet rs = stmt.executeQuery(strSql);
while(rs.next()){
String strAuID = rs.getString(1);
String strPhone = rs.getString(2);
System.out.println("AU_ID = " + strAuID + "/tPHONE = " + strPhone);
}
rs.close();
stmt.close();
con.close();
}catch(Exception ex){
System.out.print(ex.toString());
}
}
}