package exercise; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import com.mysql.jdbc.ResultSetMetaData; public class TestJdbc { public static void main(String[] args) { String sql="select Flow_ID FlowID,Type,ID_Card IDCard,Exam_Card ExamCard"+"Student_Name StudentName,Location,Grade from examstudent where Flow_Id=?"; Student stu= get(Student.class,sql,1); System.out.println(stu); //sql=" select FlowID,Type,IDCard,ExamCard"+"StudentName,Location,Grade from examstudent where FlowId=?"; } public static <T> T get(Class<T> clazz, String sql,Object...args){ T entity=null; Student stu=null; Connection connection=null; PreparedStatement preparedStatement=null; ResultSet rs=null; try { Class.forName("com.mysql.jdbc.Driver"); connection=DriverManager.getConnection// ("jdbc:mysql://localhost:3306/test", "root", "123456"); preparedStatement=connection.prepareStatement(sql); for(int i=0;i<args.length;i++){ preparedStatement.setObject(i+1, args[i]); } rs= preparedStatement.executeQuery(); //创建一个Map对象 键:列的别名 值:列的值 Map<String, Object> values=new HashMap<String,Object>(); //得到ResultSetMetaData对象 ResultSetMetaData rsmd=(ResultSetMetaData) rs.getMetaData(); //处理结果集,填充map对象 while(rs.next()){ for(int i=0;i<rsmd.getColumnCount();i++){ String columnLabel=rsmd.getColumnLabel(i+1); //为键和值 赋值,并放在values里面 Object columnValues=rs.getObject(columnLabel); values.put(columnLabel, columnValues); } } //遍历 Map 对象, 利用反射为 Class 对象的对应的属性赋值. if(values.size()>0){ entity=clazz.newInstance(); for(Map.Entry<String, Object> entry: values.entrySet()){ String FieldName=entry.getKey(); Object FieldValues=entry.getValue(); ReflectionUtils.setFieldValue(entity, FieldName, FieldValues); } } System.out.println(entity); if(rs.next()){ entity=(T) clazz.newInstance(); stu.setFlowID(rs.getInt(1)); stu.setType(rs.getString(2)); stu.setIDCard(rs.getString(3)); stu.setExamCard(rs.getString(4)); stu.setStudentName(rs.getString(5)); stu.setLocation(rs.getString(6)); stu.setGrade(rs.getInt(7)); } } catch (Exception e) { e.printStackTrace(); }finally{ if(preparedStatement!=null){ try { preparedStatement.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(connection!=null){ try { connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } return entity; } }