All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.mario6.common.db.datasource.JdbcDataSource Maven / Gradle / Ivy

The newest version!
package com.mario6.common.db.datasource;

import com.mario6.common.db.DataAccessException;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * Jdbc数据源
 */
public class JdbcDataSource extends AbstractDataSource {

    private String url;
    private String username;
    private String password;

    private JdbcDataSource(String url) {
        this.url = url;
    }

    private JdbcDataSource(String url, String username, String password) {
        this.url = url;
        this.username = username;
        this.password = password;
    }

    @Override
    public Connection getConnection() throws SQLException {
        if(username == null || "".equals(username)) {
            return DriverManager.getConnection(url);
        }
        return DriverManager.getConnection(url, username, password);
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return getConnection();
    }

    /**
     * 获得数据连接源头
     * @param config
     * @return
     */
    public static JdbcDataSource createInstance(Properties config) {
        try {
            return JdbcDataSourceFactory.createDateSource(config);
        } catch (Exception e) {
            throw new DataAccessException("创建数据源异常", e);
        }
    }

    /**
     * 数据源工厂类
     */
    private static class JdbcDataSourceFactory {
        public static JdbcDataSource createDateSource(Properties config) throws Exception {
            String driver = config.getProperty("jdbc.driver");
            String url = config.getProperty("jdbc.url");
            String username = config.getProperty("jdbc.username");
            String password = config.getProperty("jdbc.password");
            Class.forName(driver);
            return new JdbcDataSource(url, username, password);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy