The following example demonstrates how Java application connects to SQL Server 2000 through JNDI

Source: Internet
Author: User

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 ());
}
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.