Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save WizardlyBump17/7a1e9687a899d7e2b96894bbbecd8335 to your computer and use it in GitHub Desktop.
Save WizardlyBump17/7a1e9687a899d7e2b96894bbbecd8335 to your computer and use it in GitHub Desktop.
beta version of my .sql reader 😳
@RequiredArgsConstructor
public class SQLUtil {
private static final Pattern PLACEHOLDER = Pattern.compile("\\{[a-zA-Z0-9_?]+}");
private static final Connection CONNECTION;
static {
Connection con;
try {
con = DriverManager.getConnection("jdbc:mysql://192.168.2.104:3306/wlib", "davi", "");
} catch (SQLException e) {
e.printStackTrace();
con = null;
}
CONNECTION = con;
}
private final String[] commands;
public List<CachedRowSet> execute(Placeholder... placeholders) {
List<CachedRowSet> rows = new ArrayList<>();
for (String command : commands) {
try {
PreparedStatement statement = CONNECTION.prepareStatement(command.replaceAll(PLACEHOLDER.pattern(), "\\?"));
for (int i = 1; PLACEHOLDER.matcher(command).find(); i++) {
Matcher matcher = PLACEHOLDER.matcher(command);
if (!matcher.find()) break;
String extracted = command.substring(matcher.start() + 1, matcher.end() - 1);
command = command.replaceFirst(PLACEHOLDER.pattern(), "\\?");
for (Placeholder placeholder : placeholders) {
if (extracted.equals(placeholder.placeholder)) {
statement.setObject(i, placeholder.replacer);
break;
}
}
}
if (statement.execute()) {
CachedRowSetImpl row = new CachedRowSetImpl();
row.populate(statement.getResultSet());
rows.add(row);
}
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return rows;
}
public static SQLUtil read(File file) throws FileNotFoundException {
Scanner scanner = new Scanner(file);
List<String> commands = new ArrayList<>();
StringBuilder builder = new StringBuilder();
while (scanner.hasNextLine()) {
String line = scanner.nextLine().trim();
builder.append(line).append(' ');
if (line.endsWith(";")) {
commands.add(builder.toString().trim());
builder = new StringBuilder();
}
}
scanner.close();
return new SQLUtil(commands.toArray(new String[0]));
}
public static void main(String[] args) throws FileNotFoundException, URISyntaxException {
execute(
read(new File(SQLUtil.class.getClassLoader().getResource("create_tables.sql").toURI()))
);
}
static void execute(SQLUtil util, Placeholder... placeholders) {
List<CachedRowSet> execute = util.execute(placeholders);
System.out.println("any query?: " + !execute.isEmpty());
}
@Data
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
public static class Placeholder {
final String placeholder;
final Object replacer;
public static Placeholder of(String placeholder, Object replacer) {
return new Placeholder(placeholder, replacer);
}
}
}
@WizardShelby
Copy link

q

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment