Saturday, July 23, 2011

JNDI Example

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;

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

public class Test {
public static void main(String a[]) throws SQLException {
// System.out.println("test java ");
Context ctx = null;
Hashtable ht = new Hashtable();
ht.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
ht.put(Context.PROVIDER_URL, "t3://localhost:7001");

try {
ctx = new InitialContext(ht);
DataSource ds = (DataSource)ctx.lookup("myjndi");
Connection con = ds.getConnection();
Statement st =con.createStatement();
ResultSet rs =st.executeQuery("select * from user");

while (rs.next()) {
System.out.println("user name : "+rs.getString("userid"));
System.out.println("pwd : "+rs.getString("pwd"));
}

// Use the context in your program
} catch (NamingException e) {
e.printStackTrace();
// a failure occurred
} finally {
try {
ctx.close();
} catch (Exception e) {
e.printStackTrace();
// a failure occurred
}
}

}
}