protected Connection con;
protected PreparedStatement pps;
protected ResultSet rs;
protected static String url;
protected static String username;
protected static String password;
// 1.只会加载一次
static {
// 加载属性文件
try {
Properties p = new Properties();
InputStream in = DBUtil.class.getClassLoader().getResourceAsStream("db.properties");
p.load(in);
Class.forName(p.getProperty("driver"));
url = p.getProperty("url");
username = p.getProperty("username");
password = p.getProperty("password");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 2.获得链接
protected Connection getcon() {
try {
con = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
// 3.得到预状态通道
private void prepare(String sql) {
getcon();
try {
pps = con.prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
}
}
// 4.绑定参数 List用来保存参数集合
private void bangding(String sql, List params) {
try {
prepare(sql);
if (params != null && params.size() > 0) {
for (int i = 0; i < params.size(); i++) {
pps.setObject(i + 1, params.get(i));
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public <T> List<T> query(String sql, List<T> params, Class<T> clazz) {
List<T> list = new ArrayList<T>();
try {
bangding(sql, params);
rs = pps.executeQuery();
//获取实体类所有公有方法
Method[] methods = clazz.getMethods();
List<Method> SetMethods = new ArrayList<Method>();
for (Method method : methods) {
String methodName = method.getName();
//找出所有set方法放入集合
if (methodName.startsWith("set")) {
SetMethods.add(method);
}
}
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
while (rs.next()) {
//创建对象
T t = clazz.newInstance();
//遍历结果集
for (int i = 1; i <= columnCount; i++) {
//遍历set方法
for (Iterator<Method> iterator = SetMethods.iterator(); iterator.hasNext();) {
Method method = (Method) iterator.next();
String setMethodName = method.getName().toLowerCase().substring(3, method.getName().length());
//如果set方法与结果集所在列匹配,执行set方法,将结果集的值赋值给上面创建的对象
if (setMethodName.equals(metaData.getColumnName(i))) {
method.invoke(t, rs.getObject(i));
}
}
}
//将对象加入集合
list.add(t);
}
} catch (SQLException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
| InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
DBUtil查询数据库功能实现(反射)
最新推荐文章于 2022-02-14 10:55:33 发布