PreparedStatement template policy
Oleg Sobolev
sobolev.ov at gmail.com
Thu Dec 9 20:25:29 UTC 2021
I want to implement a template policy which safely generates
PreparedStatement with ?-parameter substitution. I have a problem with
null values:
public class PreparedStatementPolicy implements
TemplatePolicy<PreparedStatement, SQLException>{
private final Connection connection;
public PreparedStatementPolicy(Connection connection) {
this.connection = connection;
}
@Override
public PreparedStatement apply(TemplatedString templatedString)
throws SQLException {
String sql = templatedString.template().replace('\uFFFC', '?');
PreparedStatement ps = connection.prepareStatement(sql);
List<Object> values = templatedString.values();
for (int i = 0; i < values.size(); i++) {
int index = i + 1;
Object value = values.get(i);
if (value == null) {
int type = Types.VARCHAR; // todo: how to determine
it, could be INTEGER as well???
ps.setNull(index, type);
} else {
// set nonnull parameter...
}
}
return ps;
}
public static void main(String[] args) {
Connection connection = ...;
PreparedStatementPolicy prepare = new
PreparedStatementPolicy(connection);
String name = null;
PreparedStatement ps = prepare."update tab set name = \{name}";
}
}
The question is: how to determine which of Types.* constants to use in
the case of a null parameter value? For this I need to get the static
type of a parameter from a TemplatedString, but it is not available.
There are workarounds, but they either require additional database
roundtrips or library user inconvenience.
Is it possible to add information about static types of template
parameters to TemplatedString?
More information about the amber-dev
mailing list