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

com.wizarius.orm.database.mysql.driver.MysqlDriver Maven / Gradle / Ivy

There is a newer version: 0.0.27.3
Show newest version
package com.wizarius.orm.database.mysql.driver;


import com.wizarius.orm.database.ConnectionDriver;
import com.wizarius.orm.database.exceptions.DBException;
import com.wizarius.orm.defaultentityes.StringKeyValueList;
import lombok.extern.slf4j.Slf4j;

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

@Slf4j
public class MysqlDriver implements ConnectionDriver {
    private final String url;
    private final String driver;
    private final String username;
    private final String password;

    public MysqlDriver(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:mysql://" + hostname + ":" + port + "/" + databaseName + sb.toString();
    }

    /**
     * Get connection by initialized values
     *
     * @return connection
     */
    @Override
    public Connection getConnection() throws DBException {
        log.trace("Get mysql 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 url;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy