查询功能的包装类

/*
*查询类的接口
*/
package som.gu.core;

import java.util.List;

/**
 * 提供查询服务的核心类
 * @author 谷
 *
 */
public interface Query {

    /**
     * 执行一个DML语句
     * @param sqlDML语句
     * @param param 参数
     * @return 返回受影响的行数
     */
    int executeDML(String sql,Object[]params);
    /**
     * 插入一个对象
     * @param clazz
     * @param obj
     */
    void insert (Object obj);
    /**
     * 
     * @param clazz对应的记录所在表对象
     * @param id主键
     * @return
     */
    
    void delete(Class clazz,Object id);//delete from clazz where id=id
    
    /**
     *删除对应记录
     * @param obj记录对应的对象
     */
    void delete(Object obj);
    /**
     * 
     * @param obj要更新的对象
     * @param files要更新的字段
     */
    void update(Object obj,String[]files);//update users set name=? ss=?
    /**
     * 
     * @param clazz记录对应的类
     * @param sql查询语句
     * @param params,sql的参数
     * @return 查询到的记录
     */
    List queryRows(Class clazz,String sql,Object[]params);//查询
    
    /**
     * 
     * @param clazz记录对应的类
     * @param sql查询语句
     * @param params,sql的参数
     * @return 查询到的记录
     */
    Number queryNumber(Class clazz,String sql,Object[]params);//查询
}
/*
*实现类
*/
package som.gu.core;

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 som.gu.po.Users;

import com.gu.bean.columnInfo;
import com.gu.bean.tableInfo;
import com.gu.utils.JdbcUtils;
import com.gu.utils.StringUtils;
import com.gu.utils.reflectUtils;

public class MysqlQuery implements Query {

    

    public static void main(String[] args) {
        //删除一个对象
        /*Users us=new Users();
        us.SetId(11);
        new MysqlQuery().delete(us);*/
        //插入一个对象
        /*Users us=new Users();
        us.SetUser("tom");
        us.SetPassword("43343");
        new MysqlQuery().insert(us);*/
        //更新一个对象
        /*Users us=new Users();
        us.SetUser("jerry");
        us.SetId(12);
        new MysqlQuery().update(us,new String[]{"user"});*/
        //查询多行
        Users us=new Users();
        
        List<Users> list=new MysqlQuery().queryRows(us.getClass(),"select * from users where id>? and id<13 ", new Object[]{10});
        for(Users obj:list){
            System.out.println(obj.GetUser());
        }
    }
    
    @Override
    public int executeDML(String sql, Object[] params) {
        Connection conn=DBManager.getConnect();
        PreparedStatement ps=null;
        int count=0;
        try {
            ps=conn.prepareStatement(sql);
            JdbcUtils.handleParams(ps, params);
            count=ps.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            DBManager.closeRes(null, ps, conn);
        }
        
        return count;
    }

    @Override
    public void delete(Class clazz, Object id) {
        //class user,id=11
        //delete from user where id=?
        tableInfo info=tableContext.poClassTableMap.get(clazz);
        columnInfo onlyKey=info.getOnlyKey();
        String sql="delete from "+ info.gettName()+ " where "+onlyKey.getName()+" =?";
        System.out.print(sql);
        executeDML(sql, new Object[]{id});
    }

    @Override
    public void delete(Object obj) {
        Class c=obj.getClass();
        tableInfo info=tableContext.poClassTableMap.get(c);
            columnInfo onlyKey=info.getOnlyKey();//主键
        //通过反射获得对应的get,set方法
        Object onlypriKey=reflectUtils.invokeGet(onlyKey.getName(), obj);
        delete(c,onlypriKey);
        
    }

    @Override
    public void update(Object obj, String[] files) {
        //update table set name=?,id=?where key=?
        Class c=obj.getClass();
        tableInfo table=tableContext.poClassTableMap.get(c);
        columnInfo onlyKey=table.getOnlyKey();
        StringBuilder sql=new StringBuilder("update "+table.gettName()+" set ");
        List<Object>params=new ArrayList<>();
        for(String fName:files){
            Object fValue=reflectUtils.invokeGet(fName, obj);
            params.add(fValue);
            sql.append(fName+"=?,");
        }
        sql.setCharAt(sql.length()-1, ' ');
        sql.append("where "+onlyKey.getName()+"=?;");
        params.add(reflectUtils.invokeGet(onlyKey.getName(), obj));
    //    System.out.print(sql.toString());
        executeDML(sql.toString(), params.toArray());
    }

    @Override
    public List queryRows(Class clazz, String sql, Object[] params) {
        //query *from table where id=?//user=?//pa=?
        Connection conn=DBManager.getConnect();
        PreparedStatement ps=null;
        List<Object>list=new ArrayList<>();
        ResultSet rs=null;
        
        try {
            ps=conn.prepareStatement(sql);
            JdbcUtils.handleParams(ps, params);//set sql语句中的参数
            
            
            rs=ps.executeQuery();
            ResultSetMetaData metaDate=rs.getMetaData();
            while(rs.next()){
                Object RowObj=null;
                try {
                    RowObj = clazz.newInstance();
                } catch (InstantiationException e) {
                    
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    
                    e.printStackTrace();
                }//调用JavaBean的无参构造器
                for(int i=0;i<metaDate.getColumnCount();i++){
                    String columnName=metaDate.getColumnLabel(i+1);
                    Object columnValue=rs.getObject(i+1);
                    //调用set方法将属性值设进去
                    reflectUtils.invokeSet( columnName,columnValue, RowObj);
                    
                }
                list.add(RowObj);
            }
            
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            DBManager.closeRes(null, ps, conn);
        }
        
        return list;
        
    }

    @Override
    public Number queryNumber(Class clazz, String sql, Object[] params) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void insert(Object obj) {
        //insert into table ()values(???);
        Class c=obj.getClass();
        tableInfo table=tableContext.poClassTableMap.get(c);
        List<String>params=new ArrayList<>();//不为空的参数名
        List<Object>values=new ArrayList<>();
        int count=0;//计算参数个数
        StringBuilder sql=new StringBuilder("insert into "+table.gettName()+" (");
        Field[] fields=c.getDeclaredFields();//反射获得属性数组
        for(Field f:fields){//获得属性名和属性值
            String fName=f.getName();
            Object fValue=reflectUtils.invokeGet(fName, obj);
            if(fValue!=null){
                count++;
                params.add(fName);
                sql.append(fName+",");
                values.add(fValue);
            }
        }
        sql.setCharAt(sql.length()-1, ')');
        sql.append(" values(");
        for(int i=0;i<count;i++){
            sql.append("?,");
        }
        sql.setCharAt(sql.length()-1, ')');
        sql.append(";");
        
        
        executeDML(sql.toString(), values.toArray());
    }

}
原文地址:https://www.cnblogs.com/helloMyworld0001/p/5972952.html