import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
+import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
*/
public class DbTester extends ExternalResource {
+ private static final Joiner COMMA_JOINER = Joiner.on(", ");
private final System2 system2;
private final TestDb db;
private DbClient client;
return client;
}
- public void executeUpdateSql(String sql) {
+ public void executeUpdateSql(String sql, String... params) {
try (Connection connection = db.getDatabase().getDataSource().getConnection()) {
- new QueryRunner().update(connection, sql);
+ new QueryRunner().update(connection, sql, params);
} catch (Exception e) {
throw new IllegalStateException("Fail to execute sql: " + sql, e);
}
* Very simple helper method to insert some data into a table.
* It's the responsibility of the caller to convert column values to string.
*/
- public void executeInsert(String table, Map<String, String> valuesByColumn){
+ public void executeInsert(String table, Map<String, String> valuesByColumn) {
if (valuesByColumn.isEmpty()) {
throw new IllegalArgumentException("Values cannot be empty");
}
- String sql = "insert into " + table.toLowerCase() + " (" +
- Joiner.on(", ").join(valuesByColumn.keySet()) +
- ") values ('" +
- Joiner.on("', '").join(valuesByColumn.values()) +
- "')";
- executeUpdateSql(sql);
+
+ String sql = "insert into " + table.toLowerCase(Locale.ENGLISH) + " (" +
+ COMMA_JOINER.join(valuesByColumn.keySet()) +
+ ") values (" +
+ COMMA_JOINER.join(Collections.nCopies(valuesByColumn.size(), '?')) +
+ ")";
+ executeUpdateSql(sql, valuesByColumn.values().toArray(new String[valuesByColumn.size()]));
}
/**
dbTester.executeInsert(USERS_DB_TABLE, ImmutableMap.of(LOGIN_DB_COLUMN, "login1", NAME_DB_COLUMN, "name one"));
dbTester.executeInsert(USERS_DB_TABLE, ImmutableMap.of(LOGIN_DB_COLUMN, "login2", NAME_DB_COLUMN, "name two"));
- dbTester.commit();
-
try (Connection connection = dbTester.openConnection()) {
List<String[]> users = underTest.executeSelect(connection, "select " + LOGIN_DB_COLUMN + ", " + NAME_DB_COLUMN + " from users order by id", new SqlExecutor.StringsConverter(
2));
@Test
public void executeUpdate_executes_PreparedStatement() throws Exception {
dbTester.executeInsert(USERS_DB_TABLE, ImmutableMap.of(LOGIN_DB_COLUMN, "the_login", NAME_DB_COLUMN, "the name"));
- dbTester.commit();
try (Connection connection = dbTester.openConnection()) {
underTest.executeUpdate(connection, "update users set " + NAME_DB_COLUMN + "='new name' where " + LOGIN_DB_COLUMN + "='the_login'");
- connection.commit();
}
Map<String, Object> row = dbTester.selectFirst("select " + NAME_DB_COLUMN + " from users where " + LOGIN_DB_COLUMN + "='the_login'");
+ assertThat(row).isNotEmpty();
assertThat(row.get("NAME")).isEqualTo("new name");
}