---
title: "JNDI使用测试"
author: "kinkding"
date: "2010-07-15T18:22:20Z"
tags: []
categories: ["编程语言"]
slug: "jndi"
draft: false
lastmod: "2010-07-15T18:22:20Z"
id: 713756
url: "https://kinkding.iteye.com/blog/713756"
---

package filesplit;

import java.sql.Connection;  
import java.sql.PreparedStatement;  
import java.sql.ResultSet;  
import java.sql.SQLException;  
import java.util.Hashtable;

import javax.naming.InitialContext;  
import javax.naming.NamingException;  
import javax.sql.DataSource;

public class JNDITest {  
    public static void main(String\[] args) {  
        String jndiName = "CTDataSource";  
        String url = "t3://10.10.5.29:9200";  
        JNDITest jtest = new JNDITest();  
        try {  
            jtest.testjndi(jndiName, url);  
        } catch (NamingException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (SQLException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
    }

    public void testjndi(String jndiName, String url) throws NamingException,  
            SQLException {  
        Hashtable arg = new Hashtable();  
        arg.put("java.naming.provider.url", url);  
        arg.put("java.naming.factory.initial",  
                "weblogic.jndi.WLInitialContextFactory");

        InitialContext objCtx = new InitialContext(arg);  
        DataSource ds = (DataSource) objCtx.lookup(jndiName);

        Connection conn = ds.getConnection();  
        PreparedStatement pstmt = conn  
                .prepareStatement("select USER\_ID,NAME from pub\_user where DEPARTMENT\_ID=0");  
        ResultSet rs = pstmt.executeQuery();  
        while (rs.next()) {  
            System.out.println(rs.getString("USER\_ID") + ","  
                    + rs.getString("NAME"));  
        }  
        rs.close();  
        pstmt.close();  
        conn.close();

    }

}

 

得到的结果如下：

00000495,hpbac  
00000503,test12  
00000969,hang

 

运转良好。