convert SQL and binding data to straight SQL
I have a custom Java query engine that produces a String of SQL (with ? as data placeholders) and a List of objects containing the data to bind to the placeholders. This is then passed to JDB开发者_StackOverflow社区CTemplate.queryForList(sql, bindings.toArray()) API to produce a result set.
This works fine, but I also need to use this SQL in a subquery and can't figure out an (easy way) to convert from this to straight SQL (using the proper database conversion between Java types and database friendly formatting, etc).
Is there a utility to do this?
You might want to look at the following utility.
http://commons.apache.org/dbutils/
While this won't answer your question directly, it might be useful in the future. I have run into this issue as well and I devised a method that worked for me albeit not the best. I created a method that auto fills the values from parameters as you suggested but it doesn't do it in a type-safe way at all. Anyways, maybe you can take the method and improve upon it if you do decide to use it:
public static String preparedQueryString(String staticQuery, Object... parameters) {
for(Object curParameter : parameters) {
if(curParameter instanceof String) {
staticQuery = staticQuery.replaceFirst("\\?", "'" + curParameter.toString() + "'");
} else {
staticQuery = staticQuery.replaceFirst("\\?", curParameter.toString());
}
return staticQuery;
}
You might also want to add code to make sure the number of parameters doesn't exceed the number of Question Marks and you might also want to make the java types convert more appropriately to the database your using. I used this to output the SQL of the PreparedStatement as the PreparedStatement doesn't have any nice features that let you rip out the finished SQL query after setting the appropriate parameters.
Hope this helps,
精彩评论