当前位置: 代码迷 >> 综合 >> BaseDao(反射)
  详细解决方案

BaseDao(反射)

热度:101   发布时间:2023-10-22 14:55:20.0

不解释,直接上代码: 

package com.kyxm.dao.impl;import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;/*** * @author author** @date  2017-4-21** @connect  database*/public class BaseDao {private final static String DRIVER = "com.mysql.jdbc.Driver";private final static String URL = "jdbc:mysql://localhost:3306/yc_kygl_test";private static final String USER = "root";private static final String PASS = "123";  static {try {Class.forName(DRIVER);//加载驱动} catch (ClassNotFoundException e) {e.printStackTrace();}}public static Connection getConn() {Connection conn = null;try {conn = DriverManager.getConnection(URL, USER, PASS);//获取连接} catch (SQLException e) {e.printStackTrace();}return conn;}//	更新操作public boolean operUpdate(String sql, List<Object> p) {Connection conn = null;PreparedStatement pste = null;int res = 0;conn = getConn();try {pste = conn.prepareStatement(sql);if(p != null) {for(int i = 0; i < p.size(); i++) {pste.setObject(i+1, p.get(i));}}res = pste.executeUpdate();//} catch (SQLException e) {e.printStackTrace();} finally {releaseAll(null, pste, conn);}return res > 0;//0则失??}//	查询操作public <T> List<T> operQuery(String sql, List<Object> p, Class<T> cls) throws Exception{Connection conn = null;PreparedStatement pste = null;ResultSet rs = null;List<T> list = new ArrayList<T>();conn = getConn();try {pste = conn.prepareStatement(sql);if(p != null) {for(int i = 0; i <p.size(); i++) {pste.setObject(i+1, p.get(i));}}rs = pste.executeQuery();ResultSetMetaData rsmd = rs.getMetaData();while(rs.next()) {T m = cls.newInstance();for(int j = 0; j < rsmd.getColumnCount(); j++) {//从数据库中取得字段名String col_name = rsmd.getColumnName(j+1);Object value = rs.getObject(col_name);//构建属性名 ps:company_id——>companyIdString fildName = null;StringBuffer sb = new StringBuffer();String names[] = col_name.split("_");for(int i = 0;i < names.length;i ++){if(i==0){sb.append(names[i]);}else{//将字符串"_"后一位变为大写sb.append(names[i].substring(0, 1).toUpperCase()+names[i].substring(1));}}fildName = sb.toString();Field field = cls.getDeclaredField(fildName);field.setAccessible(true);field.set(m, value);}list.add(m);}} catch (SQLException e) {e.printStackTrace();} finally {releaseAll(rs,pste,conn);}return list;}//	关闭连接,释放资源private void releaseAll(ResultSet res, PreparedStatement pste, Connection conn) {try {if(res != null) res.close();if(pste != null) pste.close();if(conn != null) conn.close();} catch (SQLException e) {e.printStackTrace();}}}