反射的应用,jdbc封装

实现在Java中查询数据库并保存在Java中

 1.创建Dept类(要查找的类)

package cn.ljs;

public class Dept {
	private int deptno;
	private String dname;
	private String loc;

	public int getDeptno() {
		return deptno;
	}

	public void setDeptno(int deptno) {
		this.deptno = deptno;
	}

	public String getDname() {
		return dname;
	}

	public void setDname(String dname) {
		this.dname = dname;
	}

	public String getLoc() {
		return loc;
	}

	public void setLoc(String loc) {
		this.loc = loc;
	}

	public Dept() {
		super();
	}

	public Dept(int deptno, String dname, String loc) {
		super();
		this.deptno = deptno;
		this.dname = dname;
		this.loc = loc;
	}

	@Override
	public String toString() {
		return "Dept [deptno=" + deptno + ", dname=" + dname + ", loc=" + loc
				+ "]";
	}

}

  

 2.自定义的工具类

package cn.ljs.utill;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class Jdbcutill {


	private static String drive = "";
	private static String url = "";
	private static String user = "";
	private static String password = "";

	static {
		try {
			// 以流的形式获取db.properties
			InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties");
					
			// 创建Properties 类,通过load流读取到该对象中
			Properties prop = new Properties();
			prop.load(in);
			drive = prop.getProperty("drive");
			url = prop.getProperty("url");
			user = prop.getProperty("user");
			password = prop.getProperty("password");
			
			System.out.println(drive);
			System.out.println(url);
			System.out.println(user);
			System.out.println(password);

			// 1.加载数据库驱动类
			Class.forName(drive);
			

		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("配置文件失败");
		}
	}

	public static Connection getConnection() {
		Connection connection = null;
		try {
			connection = DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return connection;

	}

	public static void close(Connection conn, PreparedStatement ps, ResultSet rs) {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (ps != null) {
			try {
				ps.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

3.配置文件

# do not write space
drive=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
user=SCOTT
password=tiger

4实现在Java中查询数据库并保存在Java中    

package cn.ljs;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.ljs.utill.Jdbcutill;

public class TestUser {
    public static void main(String[] args) throws Exception {
        TestUser testUser = new TestUser();
        List list = testUser.rowToBean("select * from dept", Dept.class);
        for (int i = 0; i < list.size(); i++) {
            Dept dept = (Dept)list.get(i);
            System.out.println(dept);
        }
    }
    
    
    public List rowToBean(String sql,Class cls) throws Exception{
        List list = new ArrayList<>();
        //调用自定义的方法,加载数据库,创建数据库的连接对象
        Connection conn = Jdbcutill.getConnection();
        //创建预编译对象,结果集对象
        PreparedStatement ps= null;
        ResultSet rs = null;
        
        ps = conn.prepareStatement(sql);
        rs = ps.executeQuery();
        // 每一个rs对象都对应一个ResultSetMetaData对象
        ResultSetMetaData metaData = rs.getMetaData();
        // 获取查询的列数
        int count = metaData.getColumnCount();
        
        //遍历
        while(rs.next()){
            Object object = cls.newInstance();
            for (int i = 0; i < count; i++) {
                //获取第几列的名字
                String fieldName = metaData.getColumnName(i+1).toLowerCase();
                //通过类名获取类中的属性的描述
                Field field = cls.getDeclaredField(fieldName);
                //通过类名,拼接的方法名,属性描述的类型获取set方法
                Method method = cls.getDeclaredMethod(getSetMethodName(fieldName),field.getType());
                //通过结果集获取数据库中的属性值
                Object objval = rs.getObject(fieldName);
                //执行setfangfa(需要类的对象名,数据库的属性值)
                if (objval != null) {
                    if (objval instanceof Number) {
                        if (field.getType().getName().equals("int")
                                || field.getType().getName().equals("java.lang.Integer")) {
                            method.invoke(object, rs.getInt(fieldName));
                        } else if (field.getType().getName().equals("long")
                                || field.getType().getName().equals("java.lang.Long")) {
                            method.invoke(object, rs.getLong(fieldName));
                        } else if (field.getType().getName().equals("double")
                                || field.getType().getName().equals("java.lang.Double")) {
                            method.invoke(object, rs.getDouble(fieldName));
                        } else if (field.getType().getName().equals("short")
                                || field.getType().getName().equals("java.lang.Short")) {
                            method.invoke(object, rs.getShort(fieldName));
                        } else if (field.getType().getName().equals("byte")
                                || field.getType().getName().equals("java.lang.Byte")) {
                            method.invoke(object, rs.getByte(fieldName));
                        } else if (field.getType().getName().equals("float")
                                || field.getType().getName().equals("java.lang.Float")) {
                            method.invoke(object, rs.getFloat(fieldName));
                        }
                    } else {
                        method.invoke(object, objval);
                    }
                }
                //关闭资源
                
                
            }
                
            list.add(object);
        }
        
        Jdbcutill.close(conn, ps, rs);    
        
        
        return list;
    }
    //拼接set方法名
    public String getSetMethodName(String fieldName){
        return "set" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);
    }

    
    
}

 

posted @ 2019-04-23 20:17  无声凉薄  阅读(349)  评论(0编辑  收藏  举报