2020-03-02 16:12:14 +01:00
|
|
|
package eu.dnetlib.dhp.migration.utils;
|
2020-01-17 15:26:21 +01:00
|
|
|
|
|
|
|
import java.io.Closeable;
|
|
|
|
import java.io.IOException;
|
|
|
|
import java.sql.Connection;
|
|
|
|
import java.sql.DriverManager;
|
|
|
|
import java.sql.ResultSet;
|
|
|
|
import java.sql.SQLException;
|
|
|
|
import java.sql.Statement;
|
|
|
|
import java.util.function.Consumer;
|
|
|
|
|
2020-02-11 12:48:03 +01:00
|
|
|
import org.apache.commons.lang3.StringUtils;
|
2020-01-17 15:26:21 +01:00
|
|
|
import org.apache.commons.logging.Log;
|
|
|
|
import org.apache.commons.logging.LogFactory;
|
|
|
|
|
|
|
|
public class DbClient implements Closeable {
|
|
|
|
|
|
|
|
private static final Log log = LogFactory.getLog(DbClient.class);
|
|
|
|
|
|
|
|
private Connection connection;
|
|
|
|
|
|
|
|
public DbClient(final String address, final String login, final String password) {
|
|
|
|
|
|
|
|
try {
|
|
|
|
Class.forName("org.postgresql.Driver");
|
2020-02-11 12:48:03 +01:00
|
|
|
|
|
|
|
this.connection =
|
|
|
|
StringUtils.isNoneBlank(login, password) ? DriverManager.getConnection(address, login, password) : DriverManager.getConnection(address);
|
2020-01-17 15:26:21 +01:00
|
|
|
this.connection.setAutoCommit(false);
|
|
|
|
} catch (final Exception e) {
|
|
|
|
log.error(e.getClass().getName() + ": " + e.getMessage());
|
|
|
|
throw new RuntimeException(e);
|
|
|
|
}
|
|
|
|
log.info("Opened database successfully");
|
|
|
|
}
|
|
|
|
|
|
|
|
public void processResults(final String sql, final Consumer<ResultSet> consumer) {
|
|
|
|
|
|
|
|
try (final Statement stmt = connection.createStatement()) {
|
2020-02-11 15:29:50 +01:00
|
|
|
stmt.setFetchSize(100);
|
|
|
|
|
2020-02-11 12:48:03 +01:00
|
|
|
try (final ResultSet rs = stmt.executeQuery(sql)) {
|
2020-01-17 15:26:21 +01:00
|
|
|
while (rs.next()) {
|
|
|
|
consumer.accept(rs);
|
|
|
|
}
|
|
|
|
} catch (final SQLException e) {
|
|
|
|
throw new RuntimeException(e);
|
|
|
|
}
|
|
|
|
} catch (final SQLException e1) {
|
|
|
|
throw new RuntimeException(e1);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
|
|
|
public void close() throws IOException {
|
|
|
|
try {
|
|
|
|
connection.close();
|
|
|
|
} catch (final SQLException e) {
|
|
|
|
throw new RuntimeException(e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|