summaryrefslogtreecommitdiff
path: root/src/database/NamedPreparedStatement.java
blob: c98edaca0f3078e509908fd5c23eb5fa96ac6fc0 (plain)
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
package database;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Allows a prepared statement to contain named parameters instead of a question
 * mark position marker.
 *
 * @author Peter Wu
 */
public class NamedPreparedStatement {

    private final List<String> fields;
    private final PreparedStatement stmt;

    public NamedPreparedStatement(Connection conn, String query) throws SQLException {
        fields = new ArrayList<>();
        Pattern pattern = Pattern.compile(":\\w+");
        Matcher matcher = pattern.matcher(query);
        while (matcher.find()) {
            fields.add(matcher.group());
        }
        String sql = query.replaceAll(pattern.pattern(), "");
        stmt = conn.prepareStatement(sql);
    }

    private List<Integer> getParamIndices(String fieldName) {
        List<Integer> indices = new ArrayList<>();
        int index = 0;
        for (String name : fields) {
            ++index;
            if (name.equals(fieldName)) {
                indices.add(index);
            }
        }
        if (indices.isEmpty()) {
            throw new RuntimeException("Missing " + fieldName + " in query!");
        }
        return indices;
    }

    public void setLong(String name, long l) throws SQLException {
        for (int paramIndex : getParamIndices(name)) {
            stmt.setLong(paramIndex, l);
        }
    }

    public void setString(String name, String str) throws SQLException {
        for (int paramIndex : getParamIndices(name)) {
            stmt.setString(paramIndex, str);
        }
    }

    public void setString(String name, int i) throws SQLException {
        for (int paramIndex : getParamIndices(name)) {
            stmt.setInt(paramIndex, i);
        }
    }

    public PreparedStatement getStmt() {
        return stmt;
    }
}