Skip to content

Instantly share code, notes, and snippets.

@chethanbandi
Last active February 17, 2021 05:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chethanbandi/5c45b10ef01d1e9cb65acb2a1e2d2f25 to your computer and use it in GitHub Desktop.
Save chethanbandi/5c45b10ef01d1e9cb65acb2a1e2d2f25 to your computer and use it in GitHub Desktop.
jdbc helper
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JdbcUtil {
private static final Pattern BINDING_COLUMN = Pattern.compile("(\\s:([a-zA-Z0-9]+)\\s)");
private JdbcUtil() {
// private constructor
}
public static void handle(String sql, Map<String, Object> bindings) throws SQLException {
Connection conn = DBFactory.dataSource().getConnection();
PreparedStatement statement = conn.prepareStatement(sql);
Map<String, Integer> bindColumnIndex = getColumnIndex(sql);
bind(statement, bindings, bindColumnIndex);
}
public static String sanitize(String sql) {
return BINDING_COLUMN.matcher(sql).replaceAll(" ? ");
}
public static void handle(PreparedStatement statement, String sql, Map<String, Object> bindings) throws SQLException {
Map<String, Integer> bindColumnIndex = getColumnIndex(sql);
bind(statement, bindings, bindColumnIndex);
}
private static Map<String, Integer> getColumnIndex(String sql) {
Map<String, Integer> columnIndex = new LinkedHashMap<>();
Matcher matcher = BINDING_COLUMN.matcher(sql);
for (int i = 1; matcher.find(); i++) {
columnIndex.put(matcher.group(2), i);
}
return columnIndex;
}
private static void bind(PreparedStatement statement, Map<String, Object> bindings,
Map<String, Integer> bindColumnIndex) throws SQLException {
Objects.requireNonNull(bindings);
Objects.requireNonNull(statement);
for (Map.Entry<String, Object> binding : bindings.entrySet()) {
int index = bindColumnIndex.get(binding.getKey());
bind(statement, index, binding.getValue());
}
}
private static void bind(PreparedStatement statement, int index, Object value) throws SQLException {
if (value instanceof Integer) {
statement.setInt(index, (Integer) value);
} else if (value instanceof String) {
statement.setString(index, (String) value);
} else if (value instanceof Date) {
statement.setDate(index, (Date) value);
} else if (value instanceof LocalDate) {
statement.setDate(index, Date.valueOf((LocalDate) value));
} else {
// TODO implement not supported
throw new RuntimeException("implement mapping for " + value.getClass().getName());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment