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

com.wizarius.orm.database.postgres.driver.PostgresSpringDriver Maven / Gradle / Ivy

The newest version!
package com.wizarius.orm.database.postgres.driver;

import org.apache.log4j.Logger;
import com.wizarius.orm.database.ConnectionDriver;
import com.wizarius.orm.database.exceptions.DBException;
import com.wizarius.orm.defaultentityes.StringKeyValueList;

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

public class PostgresSpringDriver implements ConnectionDriver {
    private static final Logger log = Logger.getLogger(PostgresSpringDriver.class.getName());

    private final String url;

    private final String driver;
    private final String username;
    private final String password;

    public PostgresSpringDriver(String driver, String username, String password, String databaseName, String hostname, int port, StringKeyValueList params) {
        this.driver = driver;
        this.username = username;
        this.password = password;
        StringBuilder sb = new StringBuilder();
        if (params != null) {
            sb.append("?");
            sb.append(params.get(0).getKey()).append("=");
            sb.append(params.get(0).getValue()).append("&");
            for (int i = 1; i < params.size(); i++) {
                sb.append(params.get(i).getKey()).append("=");
                sb.append(params.get(i).getValue()).append("&");
            }
            sb.setLength(sb.length() - 1);
        }
        this.url = "jdbc:postgresql://" + hostname + ":" + port + "/" + databaseName + sb.toString();
    }

    /**
     * Get connection by initialized values
     *
     * @return connection
     */
    @Override
    public Connection getConnection() throws DBException {
        log.debug("Get postgres connection");
        Connection con;
        try {
            Class.forName(driver);
            con = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException | SQLException ex) {
            throw new DBException("open connection error ", ex);
        }
        return con;
    }

    @Override
    public String getURL() {
        return this.url;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy