反射实现增删改查(DAO层)——修改数据

时间:2022-02-04 15:01:28
先贴出代码,后续补充自己的思路、配置文件、使用方式:
/**
*
* 修改数据
*
*/
@Override
public void updateObject(Object object, String tableName) {
StringBuilder sql = new StringBuilder("UPDATE " + tableName + " SET ");
Connection connection = null;
PreparedStatement preparedStatement = null;
// 用于存放传入的对象的参数,默认将id值(主键)的key设为0,方便条件设置
Map<Integer, Object> fieldsValues = new HashMap<Integer, Object>();
try {
for (int i = 0; i < fields.length; i++) {
fields[i].setAccessible(true); if (i == 0) {
fieldsValues.put(fields.length - 1, fields[i].get(object));
continue;
}
sql.append(fields[i].getName());
sql.append("=?");
fieldsValues.put(i - 1, fields[i].get(object));
if (i < (fields.length - 1))
sql.append(", ");
if (i == (fields.length - 1)) {
sql.append(" WHERE ");
sql.append(fields[0].getName());
sql.append("=?");
} }
connection = DBConnection.getConnection(); preparedStatement = connection.prepareStatement(sql.toString());
Class<?> fieldClass = null;
for (int i = 1; i <= fieldsValues.size(); i++) {
/**
* 获取存入map中对象的参数的类类型,根据类类型选择preparedStatement的set方法
*/
fieldClass = fieldsValues.get(i - 1).getClass();
// 如果类类型为String.class,则执行setString
if (fieldClass.equals(String.class)) {
preparedStatement.setString(i,
(String) fieldsValues.get(i - 1));
}
// 如果类类型为Float.class,则执行setString
if (fieldClass.equals(Float.class)) {
preparedStatement.setFloat(i,
(Float) fieldsValues.get(i - 1));
}
// 如果类类型为Integer.class,则执行setString
if (fieldClass.equals(Integer.class)) {
preparedStatement.setInt(i,
(Integer) fieldsValues.get(i - 1));
}
// 如果类类型为Timestamp.class,则执行setString
if (fieldClass.equals(Timestamp.class)) {
preparedStatement.setTimestamp(i, new Timestamp(
((Date) fieldsValues.get(i - 1)).getTime()));
} }
// 执行sql语句,返回更新参数
int columnsCount = preparedStatement.executeUpdate();
System.out.println("有" + columnsCount + "条数据被更新!"); } catch (SQLException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} finally {
DBConnection.close(connection, preparedStatement, null);
} }

基本流程:(这张表结合源码备注理解应该问题不大)如果看不清楚,复制图片地址在新窗口中查看

反射实现增删改查(DAO层)——修改数据