64 lines
2.2 KiB
Java
64 lines
2.2 KiB
Java
package ru.otus.stub.helper;
|
|
|
|
import java.sql.Connection;
|
|
import java.sql.DriverManager;
|
|
import java.sql.PreparedStatement;
|
|
import java.sql.ResultSet;
|
|
import java.sql.ResultSetMetaData;
|
|
import java.sql.SQLException;
|
|
import java.util.ArrayList;
|
|
import java.util.LinkedHashMap;
|
|
import java.util.List;
|
|
import java.util.Map;
|
|
|
|
public class SqlHelper {
|
|
|
|
private final String jdbcUrl;
|
|
private final String username;
|
|
private final String password;
|
|
|
|
public SqlHelper(String jdbcUrl, String username, String password) {
|
|
this.jdbcUrl = jdbcUrl;
|
|
this.username = username;
|
|
this.password = password;
|
|
}
|
|
|
|
public int executeUpdate(String sql) {
|
|
try (Connection connection = openConnection();
|
|
PreparedStatement statement = connection.prepareStatement(sql)) {
|
|
return statement.executeUpdate();
|
|
} catch (SQLException exception) {
|
|
throw new IllegalStateException("SQL update failed: " + sql, exception);
|
|
}
|
|
}
|
|
|
|
public List<Map<String, Object>> selectRows(String sql) {
|
|
try (Connection connection = openConnection();
|
|
PreparedStatement statement = connection.prepareStatement(sql);
|
|
ResultSet resultSet = statement.executeQuery()) {
|
|
return mapRows(resultSet);
|
|
} catch (SQLException exception) {
|
|
throw new IllegalStateException("SQL query failed: " + sql, exception);
|
|
}
|
|
}
|
|
|
|
private Connection openConnection() throws SQLException {
|
|
return DriverManager.getConnection(jdbcUrl, username, password);
|
|
}
|
|
|
|
private List<Map<String, Object>> mapRows(ResultSet resultSet) throws SQLException {
|
|
final List<Map<String, Object>> rows = new ArrayList<>();
|
|
final ResultSetMetaData metaData = resultSet.getMetaData();
|
|
final int columnsCount = metaData.getColumnCount();
|
|
|
|
while (resultSet.next()) {
|
|
final Map<String, Object> row = new LinkedHashMap<>();
|
|
for (int column = 1; column <= columnsCount; column++) {
|
|
row.put(metaData.getColumnLabel(column), resultSet.getObject(column));
|
|
}
|
|
rows.add(row);
|
|
}
|
|
return rows;
|
|
}
|
|
}
|