先贴出代码,后续补充自己的思路、配置文件、使用方式:
/**
* 插入数据
*/
@Override
public void addObject(Object object, String tableName) {
StringBuilder sql = new StringBuilder("INSERT " + tableName
+ " VALUES(");
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);
fieldsValues.put(i, fields[i].get(object));
sql.append("?");
if (i < (fields.length - 1))
sql.append(", ");
}
sql.append(")");
connection = DBConnection.getConnection();
preparedStatement = connection.prepareStatement(sql.toString());
Class<?> fieldClass = null;
for (int i = 1; i <= fieldsValues.size(); i++) {
/**
* 获取存入map中对象的参数的类类型,根据类类型选择preparedStatement的set方法
*/
if (fieldsValues.get(i - 1) != null) {
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()));
}
} else {
preparedStatement.setObject(i, null);
}
}
// 执行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) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
DBConnection.close(connection, preparedStatement, null);
}
}
原文地址:https://www.cnblogs.com/caoleiCoding/p/9061924.html
时间: 2024-10-06 00:53:24