/
DatabaseQuery.java
94 lines (82 loc) · 2.94 KB
/
DatabaseQuery.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package io.tofpu.speedbridge2.model.common.database.wrapper;
import io.tofpu.speedbridge2.model.common.database.DatabaseManager;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
public class DatabaseQuery implements AutoCloseable {
private final @Nullable PreparedStatement preparedStatement;
private final @NotNull AtomicInteger setterCounter;
public static DatabaseQuery query(final @NotNull String query) {
return new DatabaseQuery(query);
}
private DatabaseQuery(final @NotNull String query) {
try {
this.preparedStatement =
DatabaseManager.getConnection().prepareStatement(query);
} catch (final SQLException exception) {
throw new IllegalStateException(exception);
}
this.setterCounter = new AtomicInteger(0);
}
public @NotNull DatabaseQuery setInt(final Integer integer) {
try {
this.preparedStatement.setInt(setterCounter.incrementAndGet(), integer);
} catch (SQLException exception) {
exception.printStackTrace();
}
return this;
}
public @NotNull DatabaseQuery setString(final String string) {
try {
this.preparedStatement.setString(setterCounter.incrementAndGet(), string);
} catch (SQLException exception) {
exception.printStackTrace();
}
return this;
}
public @NotNull DatabaseQuery setDouble(final double score) {
try {
this.preparedStatement.setDouble(setterCounter.incrementAndGet(), score);
} catch (SQLException exception) {
exception.printStackTrace();
}
return this;
}
public @NotNull DatabaseQuery setLong(final long l) {
try {
this.preparedStatement.setLong(setterCounter.incrementAndGet(), l);
} catch (SQLException exception) {
exception.printStackTrace();
}
return this;
}
public boolean execute() {
try {
return this.preparedStatement.execute();
} catch (SQLException exception) {
exception.printStackTrace();
}
return false;
}
public void executeQuery(final @NotNull Consumer<DatabaseSet> resultSetConsumer) {
try {
try (final ResultSet resultSet = this.preparedStatement.executeQuery()) {
resultSetConsumer.accept(new DatabaseSet(resultSet));
}
} catch (SQLException exception) {
exception.printStackTrace();
}
}
@Override
public void close() throws Exception {
if (this.preparedStatement == null) {
return;
}
this.preparedStatement.getConnection().close();
this.preparedStatement.close();
}
}