解析原始sql 如:将 <clmn> 转成 ? 及 clmn的值
public static String getSQLPrepare(String paramSql, Map<String, Object> toValue) {
if (paramSql == null || paramSql.length() < 1) {
return "";
}
List<Object> tempList = new ArrayList<Object>();
StringBuffer sb = new StringBuffer();
StringBuffer temp = new StringBuffer();
boolean copy = false;
for (int i = 0; i < paramSql.length(); i++) {
char c = paramSql.charAt(i);
if (!copy && c == '<') { // 碰到 "<" 后边的可以拷贝了
copy = true;
continue;
}
if (!copy) { // 没有碰到"<"之前拷贝字符
sb.append(c);
continue;
}
if (c == '<') {
sb.append("<");
sb.append(temp.toString());
temp.setLength(0);
continue;
}
if (c == '>') {
String name = temp.toString().trim();
if (name.length() == 0 || name.indexOf(" ") != -1) { // 不是参数,是"< 之间的数据 >" // 如:a<// 10 // and b// > 50
sb.append("< " + temp.toString() + " >");
temp.setLength(0);
copy = false;
} else { // 取出名字
Object t = toValue.get(name);
//判断若t为null则转成""
if (t== null) {
t = "";
}
tempList.add(t);
temp.setLength(0);
copy = false;
sb.append("?");
}
} else {
temp.append(c);
}
}
if (copy) { // 结尾只出现 "<" 没有">"时候
sb.append((new StringBuilder()).append("<").append(temp).toString());
}
toValue.put("VALUES", tempList);
return sb.toString();
}
PrepredStatement 赋值
public static synchronized PreparedStatement getPreparedStatement(Map<String, Object> val, PreparedStatement ps) throws SQLException {
List<Object> list = (List)val.get("VALUES");
for (int i = 0; i < list.size(); i++) {
Object obj = list.get(i);
if (obj instanceof String) { //String
ps.setString(i+1, (String)obj);
}
if (obj instanceof Integer) { //Integer
ps.setInt(i+1, (Integer)obj);
}
if (obj instanceof Short) { //Short
ps.setShort(i+1, (Short)obj);
}
if (obj instanceof Long) { //Long
ps.setLong(i+1, (Long)obj);
}
if (obj instanceof Double) { //Double
ps.setDouble(i+1, (Double)obj);
}
if (obj instanceof java.util.Date) { //java.util.Date
// ps.setObject(i+1, new java.sql.Date(((java.util.Date)obj).getTime()));
ps.setObject(i+1, new Timestamp(((java.util.Date)obj).getTime()));
}
if (obj instanceof java.sql.Date) { //java.sql.Date
ps.setDate(i+1, (java.sql.Date)obj);
}
}
return ps;
}