下面的範例示範了Java Application如何透過JNDI串連上SQL Server 2000

來源:互聯網
上載者:User

值得注意的是: 需要在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());
     }
  }

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.