1. 程式人生 > >反射的應用,jdbc封裝

反射的應用,jdbc封裝

tex sys getc 查找 thread cas word size urn

實現在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); } }

反射的應用,jdbc封裝