Java讀取數據源相關信息


一、采用讀取數據源配置文件的方式
package com.ofsp.utils;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class DataSourceUtil {
     public static final String DATASOURCE_FILENAME ="jdbc.properties"; //連接數據庫的數據源文件
     public static final String DATASOURCE_URL = "jdbc.url"; //數據源文件里url的key
     public static final String DATASOURCE_USERNAME = "jdbc.username";//數據源文件里用戶名的key
     public static final String DATASOURCE_PASSWORD = "jdbc.password";//數據源文件里密碼的key
 
     /**
      * 讀取配置文件信息
      * @return Properties 配置文件信息
      * @throws Exception
      */
     public static Properties getProperties() throws Exception {
         InputStream in = null;
         if (in == null) {
             // Class.getResourceAsStream() 會指定要加載的資源路徑與當前類所在包的路徑一致。例如你寫了一個MyTest類在包com.test.mycode 下,那么MyTest.class. getResourceAsStream("name") 會在com.test.mycode包下查找相應的資源。如果這個name是以 '/' 開頭的,那么就會從classpath的根路徑下開始查找。 ClassLoader.getResourceAsStream()  無論要查找的資源前面是否帶'/' 都會從classpath的根路徑下查找。
             in = Thread.currentThread().getContextClassLoader().getResourceAsStream(DATASOURCE_FILENAME); //路徑是 classpath的相對路徑, classpath 是指  WEB-INF 文件夾下的 classes 目錄
             if(in == null){
                 throw new Exception("找不到路徑為"+DATASOURCE_FILENAME+"的數據源配置文件。");
             }
         }
         Properties properties = new Properties();
         try {
             properties.load(in);
         } catch (IOException e) {
             e.printStackTrace();
         }
         return properties;
     }
 
     /**
      * 讀取配置文件獲取連接數據庫的數據庫url
      * @return String 數據庫名
      * @throws Exception
      */
     public static String getDatabaseURL() throws Exception {
          Properties p = getProperties();
          return p.getProperty(DATASOURCE_URL);
     }
 
     /**
      * 讀取配置文件獲取連接數據庫的用戶名
      * @return String 用戶名
     * @throws Exception
      */
     public static String getUserOfDatabase() throws Exception {
          Properties p = getProperties();
          return p.getProperty(DATASOURCE_USERNAME);
     }
 
     /**
      * 讀取配置文件獲取連接數據庫的密碼
      * @return String 密碼
     * @throws Exception
      */
     public static String getPasswordOfDatabase() throws Exception {
          Properties p = getProperties();
          return p.getProperty(DATASOURCE_PASSWORD);
     }
 
     /**
      * 獲取數據庫Connection
      * @return
      * @throws Exception
      */
     public static Connection getConnection() throws Exception{
         Properties p = getProperties();
         String url = p.getProperty(DATASOURCE_URL);
         String username = p.getProperty(DATASOURCE_USERNAME);
         String password = p.getProperty(DATASOURCE_PASSWORD);
         return DriverManager.getConnection(url, username, password);
     }
 
     /**
      * 獲取指定數據庫和用戶的所有表名
      * @param conn 連接數據庫對象
      * @param user 用戶
      * @param database 數據庫名
      * @return
      */
     public static List<String> getAllTableNames(Connection conn,String database,String schem,String tableName) {
         List<String> tableNames = new ArrayList<String>();
         if (conn != null) {
               try {
                    DatabaseMetaData metadata = conn.getMetaData();
                    // 表名列表
                    ResultSet rest = metadata.getTables(database, schem.toUpperCase(), tableName.toUpperCase(), new String[] {"TABLE"});
                    while (rest.next()) {
                        tableNames.add(rest.getString("TABLE_NAME"));
                    }
               } catch (SQLException e) {
                   e.printStackTrace();
               }
          }
          return tableNames;
     }
 
}
二、如果采用Spring框架的話,還可以從Spring的配置文件中獲取當前數據源:
數據源文件配置在spring-context.xml文件中,部分片斷截取:
DruidDataSource dataSource = ApplicationContextHelper.getBean("dataSource"); //獲取數據源
Connection connection = dataSource.getConnection();//獲取連接
String user = dataSource.getUsername();//獲取用戶名
注意:connection用完后一定要及時close掉,否則會出現溢出錯誤。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM