java反射實現mysql通用增刪查改

不依賴任何jar,原生實現mysql通用增刪改查操做.
開門見山,上代碼(注:如下代碼中全部的Object參數均爲對應數據表的javaBean實體類)
`//首先創建鏈接(重點在後面,這裏簡單寫一下)
public Connection getConn() throws Exception {
	Class.forName("com.mysql.jdbc.Driver");
	String url = "jdbc:mysql://localhost:3306/test" ;
	String username = "root";
	String password = "root";
	Connection conn = DriverManager.getConnection(url, username, password);
	return conn;
}

/**
 * 查詢操做,這個重點在對獲取的到的結果集進行解析,轉換成List
 * */
public List select(Object obj,Connection conn) throws Exception{
	List list = new ArrayList();
	Class cla = obj.getClass();
	//獲得類名 做爲表名查詢
	String claname = cla.getSimpleName();
	//獲得屬性數組
	Field[] fieldArr = cla.getDeclaredFields();
	String sql = "SELECT * FROM "+claname+"";
	Statement st = conn.prepareStatement(sql);
	ResultSet rs = st.executeQuery(sql);
	while(rs.next()){
		//調用無參構造方法。實例化對象obj
		Object realObj= cla.newInstance();
		for(int i = 0;i<fieldArr.length;i++){
			//拿到每一個屬性,每一個屬性做爲一個Field類的對象
			Field field = fieldArr[i];
			field.setAccessible(true);
			Class fieldClass = field.getType();
			//設置屬性值
			setValue(fieldClass, field, realObj, rs);
		}
		list.add(realObj);
	}
	return list;
}

/**
 * 查詢賦值,經過此方法解析ResultSet將字段值賦值到對象的屬性中
 * */
public void setValue(Class fieldClass,Field field,Object obj,ResultSet rs) throws Exception {
	//以下爲經常使用數據類型,若是不夠用,手動添加便可
	if(fieldClass.toString().equals("int")){
		field.set(obj, rs.getInt(field.getName()));
	}else if(fieldClass.toString().equals("long")) {
		field.set(obj, rs.getLong(field.getName()));
	}else if(fieldClass.toString().equals("float")) {
		field.set(obj, rs.getFloat(field.getName()));
	}else if(fieldClass.toString().equals("double")) {
		field.set(obj, rs.getDouble(field.getName()));
	}else if(fieldClass.toString().equals("boolean")) {
		field.set(obj, rs.getBoolean(field.getName()));
	}else if(fieldClass.toString().equals("class java.lang.String")){
		field.set(obj,rs.getString(field.getName()));
	}else if(fieldClass.toString().equals("class java.util.Date")){
		field.set(obj,rs.getDate(field.getName()));
	}
}

/**
 * 插入操做,重點在於sql語句拼接
 * */
public int add (Object obj,Connection conn) throws Exception{
	Class cla = obj.getClass();
		//獲得類名
		String claname = cla.getSimpleName();
		//獲得屬性數組
		Field[] fieldArr = cla.getDeclaredFields();
		String attributeName = "";
		String value = "";
		for(int i =0;i<fieldArr.length;i++){
			Field field = fieldArr[i];
			field.setAccessible(true);
			Class fieldClass = field.getType();
			attributeName = attributeName+field.getName()+",";
			value = getValueSql(fieldClass, field, value, obj);
		}
		//去掉末位逗號
		attributeName = attributeName.substring(0,attributeName.length()-1);
		value = value.substring(0, value.length()-1);
		String sql = "INSERT INTO "+claname+"("+attributeName+" ) VALUES ("+value+")";
		Statement st = conn.prepareStatement(sql);
		return st.executeUpdate(sql);
}

/**
 * 插入操做,獲取對象屬性值,轉換拼接成sql語句
 * */
public String getValueSql(Class fieldClass,Field field,String value,Object obj) throws Exception {
	//以下爲經常使用數據類型,若是不夠用,手動添加便可
	if(fieldClass.toString().equals("class java.lang.String")){
		value = value+"'"+(String)field.get(obj)+"',";
	}else if(fieldClass.toString().equals("int")){
		value = value +(Integer)field.get(obj)+",";
	}else if(fieldClass.toString().equals("long")){
		value = value +(Long)field.get(obj)+",";
	}else if(fieldClass.toString().equals("float")){
		value = value +(Float)field.get(obj)+",";
	}else if(fieldClass.toString().equals("double")){
		value = value +(Double)field.get(obj)+",";
	}else if(fieldClass.toString().equals("boolean")){
		value = value +(Boolean)field.get(obj)+",";
	}else if(fieldClass.toString().equals("class java.util.Date")){
		value = value +"'"+formatTimeString(((Date)field.get(obj)).getTime() / 1000)+"',";
	}
	return value;
}

/**
 * 時間類型轉換
 * */
public static String formatTimeString(long time) {
	DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	Date date = new Date();
	date.setTime(time * 1000);
	Calendar cal = Calendar.getInstance();
	cal.setTime(date);
	int iDstOffset = cal.get(Calendar.DST_OFFSET);
	if (iDstOffset > 0) {
		date.setTime(time * 1000 - iDstOffset);
	}
	return fmt.format(date);
}

/**
 * 更新操做,重點在sql語句的拼接
 * */
public int update(Object obj,String where,Connection conn) throws Exception{
	Class cla = obj.getClass();
	Field[] fieldArr = cla.getDeclaredFields();
	String valueSql = "";
	for(int i =0;i<fieldArr.length;i++){
		Field field = fieldArr[i];
		field.setAccessible(true);
		Class fieldClass = field.getType();
		valueSql = getValueSql(valueSql, field, fieldClass, obj);
	}
	valueSql = valueSql.substring(0, valueSql.length() - 1);
	String sql = "UPDATE  "+cla.getSimpleName() +" SET "+valueSql+where;
	Statement st = conn.prepareStatement(sql);
	return st.executeUpdate(sql);
}

/**
 * 更新操做,獲取對象屬性值,拼接sql
 * */
public String getValueSql(String valueSql,Field field,Class fieldClass,Object obj) throws Exception {
	valueSql = valueSql+field.getName()+"=";
	if(fieldClass.toString().equals("class java.lang.String")){
		valueSql = valueSql+"'"+(String)field.get(obj)+"',";
	}else if(fieldClass.toString().equals("int")){
		valueSql= valueSql +(Integer)field.get(obj)+",";
	}else if(fieldClass.toString().equals("long")){
		valueSql= valueSql +(Long)field.get(obj)+",";
	}else if(fieldClass.toString().equals("float")){
		valueSql= valueSql +(Float)field.get(obj)+",";
	}else if(fieldClass.toString().equals("double")){
		valueSql= valueSql +(Double)field.get(obj)+",";
	}else if(fieldClass.toString().equals("boolean")){
		valueSql= valueSql +(Boolean)field.get(obj)+",";
	}else if(fieldClass.toString().equals("class java.util.Date")){
		valueSql= valueSql +"'"+formatTimeString(((Date)field.get(obj)).getTime() / 1000)+"',";
	}
	return valueSql;
}

/**
 * 刪除操做, 這個就是簡單封裝了個方法
 * */
public int delete(Connection conn,String tableName,String keyName,int keyValue) throws SQLException {
	String sql = "DELETE from "+tableName+" where "+keyName+"="+keyValue;
	PreparedStatement st = conn.prepareStatement(sql);
	return st.executeUpdate();
}`
以上就是全部代碼,本人是在維護一個很老的項目時用到過,因此順便整理出來.須要的客官拿走即用.
第一次發帖,若有錯誤的地方請你們幫忙指出來,望你們多多包涵
相關文章
相關標籤/搜索