JNDI: Java Naming and Directory Interface.
java如何获取weblogic配置的数据源?
参考
1.在weblogic中新建一个mysql数据源,JNDI name
设成dbconn
.
2.java代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
| package common;
import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import java.sql.*; import java.util.Hashtable;
public abstract class DBUtils { private static DataSource ds = null;
static { try { Hashtable<String, String> env = new Hashtable<>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory"); env.put(Context.PROVIDER_URL, "t3://localhost:7001"); Context context = new InitialContext(env); ds = (DataSource) context.lookup("dbconn"); } catch (NamingException e) { System.out.println(e); } }
public static Connection getConn() { Connection conn = null; try { conn = ds.getConnection(); } catch (SQLException e) { System.out.println(e); } return conn; }
public static void main(String[] args) { Connection conn = null; Statement statement = null; ResultSet resultSet = null; try { conn = getConn(); statement = conn.createStatement(); resultSet = statement.executeQuery("select count(*) from tbl_user"); resultSet.next(); System.out.println(resultSet.getLong(1)); } catch (SQLException e) { System.out.println(e); e.printStackTrace(); } finally { close(resultSet); close(statement); close(conn); } }
public static void close(Connection conn) { if (conn == null) return; try { conn.close(); } catch (SQLException e) { } }
public static void close(PreparedStatement statement) { if (statement == null) return; try { statement.close(); } catch (SQLException e) { } }
public static void close(Statement statement) { if (statement == null) return; try { statement.close(); } catch (SQLException e) { } }
public static void close(ResultSet resultSet) { if (resultSet == null) return; try { resultSet.close(); } catch (SQLException e) { } } }
|
3.打开终端
~ /weblogic/user_projects/domains/base_domain/bin/setDomainEnv.sh
javac common/DBUtils.java
java -classpath /weblogic/wlserver/server/lib/weblogic.jar: common.DBUtils
其中setDomainEnv.sh文件内容
setDomainEnv.sh
额,如果直接把weblogic.jar加到build lib中,也能直接运行。。。