手动解析SQL语句

解析原始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;
	}

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值