Jndi DataSource
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import oracle.jdbc.pool.OracleDataSource;
public class JndiDataSource {
static Connection conn = null;
static Statement stmt = null;
static ResultSet rs = null;
static Context ctx = null;
static DataSource ds = null;
public static void main(String args[]) throws Exception {
String sp = "com.sun.jndi.fscontext.RefFSContextFactory";
String file = "file:/e:/JNDI";
String dataSourceName = "jdbc/myDatabase";
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, sp);
env.put(Context.PROVIDER_URL, file);
ctx = new InitialContext(env);
bindDataSource(ctx, dataSourceName);
DataSource ds = null;
ds = (DataSource) ctx.lookup(dataSourceName);
Connection conn = ds.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT Name FROM Employees");
while (rs.next())
System.out.println(rs.getString("name"));
ctx.close();
rs.close();
stmt.close();
conn.close();
ctx.close();
conn.close();
}
public static void bindDataSource(Context ctx, String dsn) throws SQLException, NamingException {
OracleDataSource ods = new OracleDataSource();
ods.setUser("yourName");
ods.setPassword("mypwd");
ods.setDriverType("thin");
ods.setDatabaseName("ORCL");
ods.setServerName("localhost");
ods.setPortNumber(1521);
ctx.rebind(dsn, ods);
}
}
Related examples in the same category