Untitled

mail@pastecode.io avatar
unknown
plain_text
3 years ago
1.9 kB
1
Indexable
Never
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import managers.FileReaderManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class ConnectToAS400 {

    private static Connection conn;

    private static final Logger LOG = LogManager.getLogger(ConnectToAS400.class);

    public ConnectToAS400() {
        createConnection();
    }


    public Connection createConnection() {
        try {
            Class.forName("com.ibm.as400.access.AS400JDBCDriver").newInstance();
            // Open a connection
            if (conn == null || conn.isClosed()) {
                conn = DriverManager.getConnection(FileReaderManager.getInstance().getConfigReader().getAS400DBConnString(), FileReaderManager.getInstance().getConfigReader().getAS400DBUser(), FileReaderManager.getInstance().getConfigReader().getAS400DBPw());
            }
        } catch (SQLException | ClassNotFoundException e) {
            LOG.error("SQLException while creating connection");
        } catch (IllegalAccessException e) {
            LOG.error("IllegalAccessException while creating connection");
        } catch (InstantiationException e) {
            LOG.error("InstantiationException while creating connection");
        }
        return conn;

    }

    public ResultSet query(String queryString) throws SQLException {
        createConnection();
        Statement stmt = conn.createStatement();
        return stmt.executeQuery(queryString);
    }

    public int executeUpdate(String queryString) throws SQLException {
        createConnection();
        Statement stmt = conn.createStatement();
        return stmt.executeUpdate(queryString);
    }

    public static void closeConnection() throws SQLException {
        conn.close();
    }
}