It is worth noting that you must set it in classpath.
Commons-dbcp-1.2.2.jar; commons-pool-1.4.jar; naming-common.jar the path to a file
These three files can be downloaded directly from the Apache website. If Tomcat is installed
You can also find
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.exe cutequery (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 ());
}
}
}