看了以前写的代码,对就是下面这个
觉得以前写的代码好烂啊!!!,重新理了一下思路,写得更规范和简练,应该效率也会高很多,用了一下下午写的连接池(半废品。。。)
下面直接上代码,代码很好理解,就是用了简单的反射,注解的部分我都写了注释
package jdbc; import util.StringUtil; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.*; import java.util.ArrayList; import java.util.List; public class DataUtil { public static int excuteUpdate(String sql, Object... objects) { Connection connection = ConnectionPool.getInstance().getCurrentConnection(); PreparedStatement preparedStatement = null; try { preparedStatement = getStateMent(connection, sql, objects); return preparedStatement.executeUpdate(); //执行sql并返回结果 } catch (SQLException e) { e.printStackTrace(); } finally { if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } } return 0; } /** * 查询单挑记录 * * @param sql 查询语句 * @param clazz 返回对象的class * @param objects 需要的参数,必须跟sql占位符的位置一一对应 * @param <T> 泛型返回 * @return 返回单个对象 */ public static <T> T queryForObject(String sql, Class<T> clazz, Object... objects) { Connection connection = ConnectionPool.getInstance().getCurrentConnection(); PreparedStatement preparedStatement = null; ResultSet resultSet = null; T object = null; try { preparedStatement = getStateMent(connection, sql, objects); resultSet = getResultSet(preparedStatement); if (resultSet.next()) { object = invokeObject(resultSet, clazz); } } catch (SQLException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } finally { close(preparedStatement, resultSet); //记得关闭 } return object; } /** *查询多条记录 * * @param sql 查询语句 * @param clazz 返回对象的class * @param objects 需要的参数,必须跟sql占位符的位置一一对应 * @param <T> 泛型返回 * * @return list */ public static <T> List<T> queryForList(String sql, Class<T> clazz, Object... objects) { Connection connection = ConnectionPool.getInstance().getCurrentConnection(); PreparedStatement preparedStatement = null; ResultSet resultSet = null; List<T> list = new ArrayList<T>(); try { preparedStatement = getStateMent(connection, sql, objects); resultSet = getResultSet(preparedStatement); while (resultSet.next()) { list.add(invokeObject(resultSet, clazz)); } } catch (SQLException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } finally { close(preparedStatement, resultSet); } return list.size() > 0 ? list : null; } private static void close(PreparedStatement preparedStatement, ResultSet resultSet) { try { if (preparedStatement != null) { preparedStatement.close(); resultSet.close(); } } catch (SQLException e) { e.printStackTrace(); } } private static <T> T invokeObject(ResultSet resultSet, Class<T> clazz) throws IllegalAccessException, InstantiationException, SQLException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException { T object = clazz.newInstance(); ResultSetMetaData metaData = resultSet.getMetaData(); for (int i = 0, count = metaData.getColumnCount(); i < count; i++) { String columnName = metaData.getColumnName(i + 1); //数据库返回结果的列名 String fieldName = StringUtil.camelName(columnName); //去掉列名中的下划线“_”并转为驼峰命名 Field field = clazz.getDeclaredField(fieldName); //根据字段名获取field String methName = setMethodName(fieldName); //拼set方法名 Class type = field.getType(); //获取字段类型 Method setMethod = clazz.getDeclaredMethod(methName, field.getType()); Object value = resultSet.getObject(i + 1); //获取字段值 setMethod.invoke(object, type.cast(value)); //强转并且赋值 } return object; } private static PreparedStatement getStateMent(Connection connection, String sql, Object... objects) throws SQLException { if (connection == null) { return null; } PreparedStatement preparedStatement = connection.prepareStatement(sql); for (int i = 0, len = objects.length; i < len; i++) { preparedStatement.setObject(i + 1, objects[i]); //给sql每个?占位符填上数据 } return preparedStatement; } private static ResultSet getResultSet(PreparedStatement statement) throws SQLException { if (statement == null) { return null; } else { return statement.executeQuery(); } } private static String setMethodName(String str) { return "set" + StringUtil.firstUpperCase(str); } }
用到了几个简单的字符串处理方法
package util; public class StringUtil { /** * 转为驼峰命名 * @param str * @return string */ public static String camelName(String str) { if (!isEmpty(str)) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0, len = str.length(); i < len; i++) { if (str.charAt(i) == ‘_‘) { while (str.charAt(i + 1) == ‘_‘) { i++; } stringBuilder.append(("" + str.charAt(++i)).toUpperCase()); } else { stringBuilder.append(str.charAt(i)); } } return stringBuilder.toString(); } return str; } /** * 判断是否为空串 * * @param str * @return */ public static boolean isBlank(String str) { if (str != null && str.length() > 0) { for (int i = 0, len = str.length(); i < len; i++) { if (!Character.isSpaceChar(str.charAt(i))) { return false; } } } return true; } /** * 判断是否为空串 ?!!! 我怎么又写了个一样的方法?!!! * @param str * @return */ public static boolean isEmpty(String str) { return str == null || str.length() == 0; } /** * 将第一个字母替换为大写 * @param str * @return */ public static String firstUpperCase(String str) { return str.substring(0, 1).toUpperCase() + str.substring(1, str.length()); } }
下面开始是测试了
首先数据库
然后测试类,跟表结构对应的
package po; import java.util.Date; public class User { private Integer id; private Integer age; private String name; private Double score; private Date createTime; private Date updateTime; //set、get 方法均省略了,但是这个是必须的 }
测试代码
import java.util.List; public class Test { public static void main(String[] args) { String sql = "select * from t_user"; List<User> list = DataUtil.queryForList(sql,User.class); System.out.println("查询多条记录:" + list); System.out.println("******************************************************************"); sql = "select * from t_user where id = ?"; User user = DataUtil.queryForObject(sql,User.class,1); System.out.println("查询单条记录:" + user); System.out.println("******************************************************************"); sql = "insert into t_user(name,score,create_time,update_time) values(?,?,now(),now())"; int t = DataUtil.excuteUpdate(sql,"大牛",66.66); System.out.println("执行插入操作结果:"+t); } }
测试结果
太晚了,先到这了,有空把我的mybatis和ioc容器也瞎j8重写一下
转载请注明出处:
大王让我写代码 00:12:24