java 代码
- package com.abc.www;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- import java.sql.*;
- import java.util.ArrayList;
- public class NewTestReflect {
- public static void main(String[] args) throws Exception {
- NewTestReflect newtestreflect=new NewTestReflect();
- newtestreflect.select("select * from test", "com.tangshun.www.Person");
- }
- private static String getSetMethodName(String columnName) {
- return "set" + columnName.substring(0, 1).toUpperCase()
- + columnName.toLowerCase().substring(1);
- }
- /**
- * 需要提供sql语句,以及操作数据库表对应的类名字(包括包名)
- * 如:select * from test;则类名字应该是 包.Test
- * Test.java是一个简单的pojo,对数据库里面的字段只有相应的set get方法
- * 如果有必要,可以增加其他相关的构造方法等
- * @param sql
- * @param className
- * @return ArrayList
- */
- public ArrayList select(String sql, String className) {
- Connection connection = null;
- PreparedStatement stmt = null;
- ResultSet rs = null;
- ArrayList paraList = new ArrayList();
- try {
- Class.forName("com.mysql.jdbc.Driver");
- connection = DriverManager.getConnection(
- "jdbc:mysql://localhost/test", "root", "123456");
- stmt = connection.prepareStatement(sql);
- rs = stmt.executeQuery();
- Object c1 = null;
- ResultSetMetaData rsmd = rs.getMetaData();//获得元数据
- int columnCount = rsmd.getColumnCount();//获得查询的列数个数
- while (rs.next()) {
- c1 = Class.forName(className).newInstance();//根据String型的类名,得到一个Object
- for (int i = 1; i <= columnCount; i++) {//循环设置该类的set方法的相关属性
- Method m = c1.getClass().getMethod(
- getSetMethodName(rsmd.getColumnName(i)),
- Class.forName(rsmd.getColumnClassName(i)));//获得方法
- m.invoke(c1, rs.getObject(rsmd.getColumnName(i)));//设置set,此处用ResultSet.getObject(String s)方法
- }
- paraList.add(c1);//增加到List中
- }
- Person p = (Person) paraList.get(0);
- System.out.println(p.getName());
- } catch (SQLException ex) {
- ex.printStackTrace();
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (NoSuchMethodException e) {
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (InstantiationException e) {
- e.printStackTrace();
- } finally {
- try {
- rs.close();
- rs = null;
- } catch (Exception ex) {
- }
- try {
- stmt.close();
- stmt = null;
- } catch (Exception ex) {
- }
- }
- try {
- connection.close();
- connection = null;
- } catch (Exception ex) {
- }
- return paraList;
- }
- }