-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNamedParamStatement.java
More file actions
67 lines (62 loc) · 2.05 KB
/
Copy pathNamedParamStatement.java
File metadata and controls
67 lines (62 loc) · 2.05 KB
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
package com.MrYusuf.NamedParamStatementExample;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
/**
* Source: http://stackoverflow.com/a/20644736
*/
public class NamedParamStatement {
public NamedParamStatement(Connection conn, String sql) throws SQLException {
int pos;
// prefix @
while((pos = sql.indexOf("@")) != -1) {
int end = findParamEnd(sql.substring(pos));
if (end == -1)
end = sql.length();
else
end += pos;
fields.add(sql.substring(pos+1,end));
sql = sql.substring(0, pos) + "?" + sql.substring(end);
}
prepStmt = conn.prepareStatement(sql);
}
private int findParamEnd(String text){
char[] charArray = text.toCharArray();
for (int i = 1; i < charArray.length; i++)
if(Pattern.matches("[a-z|A-z|0-9]",charArray[i] + "")) continue;
else return i;
return -1;
}
public PreparedStatement getPreparedStatement() {
return prepStmt;
}
public ResultSet executeQuery() throws SQLException {
return prepStmt.executeQuery();
}
public int executeUpdate() throws SQLException{
return prepStmt.executeUpdate();
}
public void close() throws SQLException {
prepStmt.close();
}
public void setObject(String name,Object value) throws SQLException {
for (int index : getIndexes(name)){
// parameter index starts from 1
prepStmt.setObject(index + 1,value);
}
}
private List<Integer> getIndexes(String name) {
List<Integer> indexes = new ArrayList<Integer>();
for (int i = 0; i < fields.size(); i++) {
if(fields.get(i).equals(name))
indexes.add(i);
}
return indexes;
}
private PreparedStatement prepStmt;
private List<String> fields = new ArrayList<String>();
}