我自己的JdbcTemplate

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.sql.DataSource;

import org.apache.catalina.tribes.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

public class JdbcTemplate {
	private static Logger logger = LoggerFactory.getLogger(JdbcTemplate.class);
	private DataSource ds;

	public DataSource getDataSource() {
		return ds;
	}

	public void setDataSource(DataSource ds) {
		this.ds = ds;
	}

	JdbcTemplate() {
	}

	public JdbcTemplate(DataSource ds) {
		setDataSource(ds);
	}

	public List<Map<String, Object>> queryForList(String sql, Object... args) {
		Connection con = null;
		try {
			logger.info(sql);
			logger.info(Arrays.toString(args));
			con = ds.getConnection();
			con.setAutoCommit(false);
			PreparedStatement ps = con.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				ps.setObject(i + 1, args[i]);
			}
			ResultSet rs = ps.executeQuery();
			return convertResult(rs);
		} catch (SQLException e) {
			logger.error(e.getMessage());
			try {
				con.close();
			} catch (SQLException e1) {
				logger.error(e1.getMessage());
			}
		} finally {
			if (con != null) {
				try {
					con.close();
				} catch (SQLException e) {
					logger.error(e.getMessage());
				}
			}
		}
		return null;

	}

	public Map<String, Object> queryForMap(String sql, Object... param) {
		List<Map<String, Object>> lst = queryForList(sql, param);
		return lst != null && lst.size() > 0 ? lst.get(0) : new HashMap<String, Object>();
	}

	public <T> T queryForObject(String sql, Class<T> clazz, Object... param) {
		T obj = null;
		if (clazz == null) {
			return obj;
		} else {
			Map<String, Object> map = queryForMap(sql, param);
			if (map != null && map.size() > 0) {
				try {
					if (clazz.getName().startsWith("java.util") || clazz.getName().startsWith("java.lang")) {
						for (Entry<String, Object> en : map.entrySet()) {
							if (en.getValue() == null) {
								continue;
							}

							Class<?> c = en.getValue().getClass();
							if (c == clazz || c.isAssignableFrom(clazz) || clazz.isAssignableFrom(c)) {
								String s = en.getValue().toString();
								obj = JSONObject.parseObject(s, clazz);
								return obj;
							}
						}
					} else {
						obj = JSONObject.parseObject(JSONObject.toJSONString(map), clazz);
						return obj;
					}
				} catch (Exception e) {
					logger.error(e.getMessage());
				}
			}
		}
		return obj;
	}

	public int queryForUpdate(String sql, Object... args) {
		int count = 0;
		Connection con = null;
		try {
			con = ds.getConnection();
			con.setAutoCommit(false);
			PreparedStatement ps = con.prepareStatement(sql);
			if (args != null) {
				for (int i = 0; i < args.length; i++) {
					ps.setObject(i + 1, args[i]);
				}
			}
			count = ps.executeUpdate();
			con.commit();
			con.close();
		} catch (SQLException e) {
			logger.error(e.getMessage());
		}
		return count;
	}

	public int queryForBatchUpdate(String sql, String[]... argsArray) {
		int count = 0;
		Connection con = null;
		try {
			con = ds.getConnection();
			con.setAutoCommit(false);
			PreparedStatement ps =con.prepareStatement(sql);
			if (argsArray != null) {
				for (int i = 0; i < argsArray.length; i++) {
					String[] args = argsArray[i];
					for (int j = 0; j < args.length; j++) {
						ps.setObject(j+ 1, args[j]);
					}
					ps.addBatch();
				}
			}

			int[] arr = ps.executeBatch();
			for (int i : arr) {
				count += i;
			}
			con.commit();
			con.close();
		} catch (SQLException e) {
			logger.error(e.getMessage());
		}
		return count;
	}

	public int queryForBatchUpdate(String sql, List<String[]> argsArray) {
		int count = 0;
		Connection con = null;
		try {
			con = ds.getConnection();
			con.setAutoCommit(false);
			PreparedStatement ps =con.prepareStatement(sql);
			if (argsArray != null) {
				for (int i = 0; i < argsArray.size(); i++) {
					String[] args = argsArray.get(i);
					for (int j = 0; j < args.length; j++) {
						ps.setObject(j + 1, args[j]);
					}
					ps.addBatch();
				}
			}

			int[] arr = ps.executeBatch();
			for (int i : arr) {
				count += i;
			}
			con.commit();
			ps.close();
			con.close();
		} catch (SQLException e) {
			logger.error(e.getMessage());
			try {
				Thread.sleep(100);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
			queryForBatchUpdate(sql, argsArray);
		}
		return count;
	}
	
	public static List<Map<String, Object>> convertResult(ResultSet rs) {
		List<Map<String, Object>> lst = new LinkedList<>();
		if (rs == null)
			return lst;

		try {
			// 得到结果集(rs)的结构信息,比如字段数、字段名等
			ResultSetMetaData md = rs.getMetaData();

			// 返回此 ResultSet 对象中的列数
			int columnCount = md.getColumnCount();

			Map<String, Object> rowData = new LinkedHashMap<>();
			while (rs.next()) {
				rowData = new LinkedHashMap<>(columnCount);
				for (int i = 1; i <= columnCount; i++) {
					rowData.put(md.getColumnName(i), rs.getObject(i));
				}
				lst.add(rowData);
			}
			rs.close();
		} catch (SQLException e) {
			logger.error(e.getMessage());
		}
		return lst;
	}
}

  

posted @ 2018-01-17 17:46  漫漫人生路总会错几步  阅读(152)  评论(0编辑  收藏  举报