import org.apache.commons.lang3.StringUtils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.*;
public class Resulttobean {
//此方法适用于任意bean
public static List<Object> resulttobean(ResultSet rs,Class clazz) throws Exception {
List<Object> list=new ArrayList();
while(rs.next()){
Object obj = clazz.newInstance();
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
for(int i=0;i<columnCount;i++){
//获取列名
String columnName = metaData.getColumnName(i+1);
String methodname="set"+ StringUtils.capitalize(columnName);
//得到列值
Object value = rs.getObject(columnName);
Field field = clazz.getDeclaredField(StringUtils.lowerCase(columnName));
Method method = clazz.getMethod(methodname, field.getType());
//执行bean的setXX方法
method.invoke(obj, value);
}
list.add(obj);
}
return list;
}
public static ResultSet getResult() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql:///mybase";
String username="root";
String password="1234";
Connection connection = DriverManager.getConnection(url, username, password);
String sql="select * from todo";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
ResultSet resultSet = preparedStatement.executeQuery();
return resultSet;
}
public static void main(String[] args) throws Exception {
ResultSet result = getResult();
Class<?> aClass = Class.forName("org.westos.resulttobean.Todo");
List<Object> resulttobean = resulttobean(result, aClass);
System.out.println(resulttobean);
}
}
Bean:
package org.westos.resulttobean;
public class Todo {
private Integer id;
private String title;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString() {
return "Todo{" +
"id=" + id +
", title='" + title + '\'' +
'}';
}
}
运行结果: