Implement HW5 stubs, API helpers, optional SQL/MQ helpers, and test coverage
This commit is contained in:
63
src/main/java/ru/otus/stub/helper/SqlHelper.java
Normal file
63
src/main/java/ru/otus/stub/helper/SqlHelper.java
Normal file
@@ -0,0 +1,63 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user