通过weblogic的数据源获得数据库连接的方法:
package com.moonsoft.datasource;
import javax.naming.NamingException;
import java.util.Hashtable;
import javax.naming.InitialContext;
import java.sql.Connection;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class TestDataSource {
public static String WEB_URL = "t3://localhost:9000";
public static String DATA_SOURCE = "JDBCDS";
public static String weblogic_context_factory =
"weblogic.jndi.WLInitialContextFactory";
public TestDataSource() {
}
public static Object lookUp() throws NamingException {
Hashtable env = new Hashtable();
env.put(InitialContext.INITIAL_CONTEXT_FACTORY, weblogic_context_factory);
env.put(InitialContext.PROVIDER_URL, WEB_URL);
InitialContext tempContext = new InitialContext(env);
return tempContext.lookup(DATA_SOURCE);
}
public static Connection getConnection() throws SQLException {
Connection conn = null;
try {
DataSource ds = (DataSource) lookUp();
if (ds == null) {
throw new SQLException("查询到空数据源!");
}
conn = ds.getConnection();
}
catch (NamingException ex) {
ex.printStackTrace();
}
return conn;
}
public static void releaseConnection(Connection conn, PreparedStatement sta,
ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
if (sta != null)
sta.close();
if (conn != null)
conn.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
public static void testSearch() {
Connection conn = null;
PreparedStatement sta = null;
ResultSet rs = null;
try {
conn = getConnection();
String sql = "select * from admin_config where config_name like ?";
sta = conn.prepareStatement(sql);
sta.setString(1,"%Sms%");
rs = sta.executeQuery();
if (rs != null) {
while (rs.next()) {
System.out.println(rs.getString(1));
}
}
}
catch (Exception ex) {
ex.printStackTrace();
}
finally {
releaseConnection(conn,sta,rs);
}
}
public static void main(String [] argv){
testSearch();
}
}