通用增删改查

链接数据库接口

package com.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public interface DBConn {

    Connection getConn();

    public void close(Connection con);
    public void close(PreparedStatement pstmt);
    public void close(ResultSet rs);
    public void close(Statement stmt);
    public void closeAll(ResultSet rs,PreparedStatement pstmt,Connection con);
}

链接数据库

package com.db.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

import com.db.DBConn;

public class DBConnJdbc implements DBConn{

    private String driver="com.mysql.jdbc.Driver";
    private String url="jdbc:mysql://localhost:3306/ebook?useUnicode=true&characterEncoding=utf-8";
    private String user = "root";
    private String password = "11111";

    public Connection getConn(){
        Connection con = null;
        try{
            Class.forName(driver);
            con=DriverManager.getConnection(url,user,password);
        }catch(Exception e){
            e.printStackTrace();
        }
        return con;
    }

    public void close(Connection con){
        try{
            if(con != null){
                con.close();
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

    public void close(PreparedStatement pstmt){
        try{
            if(pstmt != null){
                pstmt.close();
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

    public void close(ResultSet rs){
        try{
            if(rs != null){
                rs.close();
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

    public void close(Statement stmt){
        try{
            if(stmt != null){
                stmt.close();
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

    public void closeAll(ResultSet rs,PreparedStatement pstmt,Connection con) {
        try {
            if(rs != null) {
                rs.close();
                rs = null;
            }
            if(pstmt != null) {
                pstmt.close();
                pstmt = null;
            }
            if(con != null) {
                con.close();
                con = null;
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
}

package com.db.impl;

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.Statement;
import java.util.Properties;

import com.db.DBConn;

public class DBConnJdbcProp implements DBConn{

    private static Properties prop = new Properties();

    static{
        InputStream in = null;
        Class c = DBConnJdbcProp.class;
        ClassLoader loader = c.getClassLoader();
        in = loader.getResourceAsStream("jdbc.properties");
        try {
            prop.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                if(in != null){
                in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public Connection getConn(){
        String driver = prop.getProperty("driver");
        String url = prop.getProperty("url");
        String user = prop.getProperty("user");
        String password = prop.getProperty("password");
        Connection con = null;
        try{
            Class.forName(driver);
            con=DriverManager.getConnection(url,user,password);
        }catch(Exception e){
            e.printStackTrace();
        }
        return con;
    }

    @Override
    public void close(Connection con){
        try{
            if(con != null){
                con.close();
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void close(PreparedStatement pstmt){
        try{
            if(pstmt != null){
                pstmt.close();
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void close(ResultSet rs){
        try{
            if(rs != null){
                rs.close();
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void close(Statement stmt){
        try{
            if(stmt != null){
                stmt.close();
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void closeAll(ResultSet rs, PreparedStatement pstmt, Connection con) {
        try {
            if(rs != null) {
                rs.close();
                rs = null;
            }
            if(pstmt != null) {
                pstmt.close();
                pstmt = null;
            }
            if(con != null) {
                con.close();
                con = null;
            }
        }catch(Exception e) {
            e.printStackTrace();
        }

    }
}

BaseDao

package com.dao;

import java.util.List;

public interface BaseDao<Entity> {

    public int add(Entity obj) throws Exception;
    public int delete(int id) throws Exception;
    public int update(Entity obj) throws Exception;
    public Entity get(int id) throws Exception;
    public List<Entity> getList() throws Exception;

}

package com.dao.impl;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.dao.BaseDao;
import com.db.DBConn;
import com.db.impl.DBConnJdbc;

public class BaseDaoImpl<Entity> implements BaseDao<Entity>{

    DBConn db = new DBConnJdbc();
    int r=0;
    private Class clazz;

    public BaseDaoImpl(){
        clazz = this.getClass();
        Type t = clazz.getGenericSuperclass();
        ParameterizedType pe = (ParameterizedType) t;
        clazz = (Class) pe.getActualTypeArguments()[0];
        System.out.println(clazz);
    }

    //添加
    @Override
    public int add(Entity obj) throws Exception {

        Connection con = db.getConn();
        String tables = clazz.getSimpleName();
        Field[] fields = clazz.getDeclaredFields();

        String sql = "insert into " + tables + " values(null";
        for (int i = 1; i < fields.length; i++) {
            sql += ",?";
        }
        sql = sql + ")";

        System.out.println(sql);
        PreparedStatement pstmt = null;
        pstmt = con.prepareStatement(sql);

        for (int i = 1; i < fields.length; i++) {
            String name= "get"+Character.toUpperCase(fields[i].getName().charAt(0));
            name = name + fields[i].getName().substring(1);
            Method m =clazz.getMethod(name);
            Object value= m.invoke(obj);
            pstmt.setObject(i, value);
        }
        r=pstmt.executeUpdate();
        db.close(pstmt);
        db.close(con);
        return r;

    }

    //删除
    @Override
    public int delete(int id) throws Exception {
        Connection con = db.getConn();
        String tables = clazz.getSimpleName();
        Field[] fields = clazz.getDeclaredFields();

        String idName = fields[0].getName();

        String sql = "delete  from " + tables + " where "+idName+" ="+id;
        System.out.println(sql);
        PreparedStatement pstmt = null;
        pstmt = con.prepareStatement(sql);
        r=pstmt.executeUpdate();
        db.close(pstmt);
        db.close(con);
        return r;

    }

    //更新
    @Override
    public int update(Entity obj) throws Exception {
        Connection con = db.getConn();
        String tables = clazz.getSimpleName();
        String sql = "update "+tables+" set ";
        Field[] fields = clazz.getDeclaredFields();

        String idName = fields[0].getName();

        for(int i=1;i<fields.length;i++){
            sql += fields[i].getName() + "=?,";
        }
        sql = sql.substring(0,sql.length()-1)+" where "+idName+" = ?";
        System.out.println(sql);
        PreparedStatement pstmt = null;
        pstmt = con.prepareStatement(sql);
        for(int i =1;i<fields.length;i++){
            String methodName = "get"+Character.toUpperCase(fields[i].getName().charAt(0))+fields[i].getName().substring(1);
            Method m = clazz.getMethod(methodName);
            pstmt.setObject(i,m.invoke(obj));
        }

        String FiledFirstName = "get"+Character.toUpperCase(fields[0].getName().charAt(0))+fields[0].getName().substring(1);
        Method m2 = clazz.getMethod(FiledFirstName);
        pstmt.setInt(fields.length, (Integer)m2.invoke(obj));
        r=pstmt.executeUpdate();
        db.close(pstmt);
        return r;
    }

    //根据id查询
    @Override
    public Entity get(int id) throws Exception {
        Connection con = db.getConn();

        Field[] fields = clazz.getDeclaredFields();
        String idName = fields[0].getName();

        String sql = "select * from "+clazz.getSimpleName() + " where "+idName+" =" +id;
        System.out.println(sql);
        PreparedStatement pstmt = null;
        pstmt = con.prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery();
        Entity entity =(Entity) clazz.newInstance();
        if(rs.next()){
            //Field[] fields = clazz.getDeclaredFields();
            for(int i=0;i<fields.length;i++){
                String methodName = "set" +Character.toUpperCase(fields[i].getName().charAt(0))+fields[i].getName().substring(1);
                Method m = clazz.getDeclaredMethod(methodName, fields[i].getType());
                Object value = rs.getObject(fields[i].getName());
                System.out.println(methodName + "=========" + value);
                m.invoke(entity, value);
            }
        }
        db.closeAll(rs, pstmt, con);
        return entity;
    }

    //全查
    @Override
    public List<Entity> getList() throws Exception {
        Connection con = db.getConn();
        String sql = "select * from "+clazz.getSimpleName();
        PreparedStatement pstmt = null;
        pstmt = con.prepareStatement(sql);
        List<Entity> list = new ArrayList<Entity>();
        ResultSet rs = pstmt.executeQuery();
        while(rs.next()){
            Entity entrty = (Entity)clazz.newInstance();
            Field[] fields = clazz.getDeclaredFields();
            for(int i=0;i<fields.length;i++){
                String methodName = "set"+Character.toUpperCase(fields[i].getName().charAt(0))+fields[i].getName().substring(1);
                Method m = clazz.getMethod(methodName, fields[i].getType());
                m.invoke(entrty, rs.getObject(fields[i].getName()));
            }
            list.add(entrty);
        }
        System.out.println(sql);
        db.closeAll(rs, pstmt, con);
        return list;
    }

}

登录

package com.dao;

import com.entity.Person_info;

public interface Person_infoDao extends BaseDao<Person_info>{

    public boolean login(Person_info obj);
    public Person_info getLogin(String login_name);
}

package com.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.dao.Person_infoDao;
import com.db.DBConn;
import com.db.impl.DBConnJdbcProp;
import com.entity.Person_info;

public class Person_infoDaoImpl extends BaseDaoImpl<Person_info> implements Person_infoDao{

    //用户登录
    @Override
    public boolean login(Person_info obj) {

        boolean blean = false;
        String sql ="select *from person_info where login_name =? and password=?";
        DBConn db = new DBConnJdbcProp();
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try{
            con=db.getConn();
            pstmt=con.prepareStatement(sql);
            pstmt.setString(1,obj.getLogin_name());
            pstmt.setString(2,obj.getPassword());
            rs = pstmt.executeQuery();

            while(rs.next()){
                int user_id = rs.getInt("user_id");
                obj.setUser_id(user_id);;
                if(user_id>0){
                    blean = true;
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            db.close(con);
            db.close(pstmt);
            db.close(rs);
        }
        return blean;
    }

    @Override
    public Person_info getLogin(String login_name) {

        String sql ="select *from person_info where login_name =‘"+login_name+"‘";
        DBConn db = new DBConnJdbcProp();
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        Person_info pi = new Person_info();
        try {
            con = db.getConn();
            pstmt = con.prepareStatement(sql);
            rs = pstmt.executeQuery();
            while(rs.next()){
                pi.setUser_id(rs.getInt("user_id"));
                pi.setLogin_name(rs.getString("login_name"));
                pi.setPassword(rs.getString("password"));
                pi.setPost_id(rs.getInt("post_id"));
                pi.setOther(rs.getString("other"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            db.closeAll(rs, pstmt, con);
        }
        return pi;

    }

}

登录Biz

package com.biz;

import java.util.List;

import com.entity.Person_info;

public interface Person_infoBiz {

    Person_info login(Person_info obj);
    int add(Person_info obj);
    int update(Person_info obj);
    Person_info getLogin(String login_name);

    Person_info get(int id);
    List<Person_info> getList();

}

package com.biz.impl;

import java.util.List;

import com.biz.Person_infoBiz;
import com.dao.Person_infoDao;
import com.dao.impl.Person_infoDaoImpl;
import com.entity.Person_info;

public class Person_infoBizImpl implements Person_infoBiz{

    Person_infoDao dao = new Person_infoDaoImpl();

    @Override
    public Person_info login(Person_info obj) {
        dao.login(obj);
        return obj;
    }

    @Override
    public int add(Person_info obj) {
        int rs = 0;
        try{
            rs=dao.add(obj);
        }catch(Exception e){
            rs = 0;
            e.printStackTrace();
        }
        return rs;
    }

    @Override
    public int update(Person_info obj) {
        int rs = 0;
        try {
            rs=dao.update(obj);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rs;
    }

    @Override
    public Person_info getLogin(String login_name) {

        return dao.getLogin(login_name);
    }

    @Override
    public Person_info get(int id) {

        Person_info pi = null;
        try {
            pi = dao.get(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pi;
    }

    @Override
    public List<Person_info> getList() {
        List<Person_info> list = null;
        try {
            list = dao.getList();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
}

时间: 2024-10-11 15:49:40

通用增删改查的相关文章

用DBContext (EF) 实现通用增删改查的REST方法

我们用ADO.NET Entity Data Model来生成实体类后,一般都会对这些类进行基本的增删改查操作,如果每个类都要写这些基本的方法,实在太乏味了.下面就是通过step by step的方式介绍如何用DBContext来实现通用增删改查的REST方法,以及实现过程中容易出现的问题. 1. 打开vs2012,新建一个class library的项目 2. 新加一个ADO.NET Entity Data Model项到这个项目 3. 打开App.Config, 修改res://* 为res

EF学习笔记——通用增删改查方案

http://blog.csdn.net/leftfist/article/details/25005307 我刚接触EF未久,还不知道它有什么强大之处,但看上去,EF提供了一般的增删改查功能.以往用过一些ORM方法,尽管有代码生成器,但代码量总的 来说比较多.这次采用EF,我就想,能不能尽量写出一些通用的方法,以后添加表.实体类,只需做很少的改动,就能拥有基本的增删改查功能呢? 方案如下: 1. 分为几个部分:BLL.DAL.Model.Interface.其中,EF生成的代码放在Model.

通用增删改查方法

1.增删改通用的方法 传入SQL语句和SQL占位符 public static Boolean adu(String sql ,Object ...objs) { Boolean f =false; try { Connection con=DBUtil.getconnection(); PreparedStatement pst=con.prepareStatement(sql); for (int i=0;i<objs.length;i++) { pst.setObject((i+1), o

数据库连接,通用增删改查

import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class BaseDao { private static final String DRIVER="oracle.jdbc.driver.OracleDriver"; p

通用DAO之MyBatis封装,封装通用的增删改查(三)

曾将发布过俩篇关于Mybatis封装的文章,当时曾曾承诺过当测试没有问题后阿海会整理一下然后将原代码发布出来. 那么今天正好朋友找我要一份那套mybatis封装的源码,我便整理了一份,想想这么长时间了并没有发现什么明显的bug,于是决定将它发出来. 喜欢的朋友可以在这里下载: http://aiyiupload.oss-cn-beijing.aliyuncs.com/blog/img/2016/06/28/15/6d69ad50-ab53-4f4f-b4e7-1fed010bfdb9.rar 关

Java连接MySQL数据库增删改查通用方法

Java连接MySQL数据库增删改查通用方法 运行环境:eclipse+MySQL 以前我们Java连接MySQL数据库都是一个数据库写一个类,类下面写好多方法,要是多个数据库,就要写多个类多个方法,导致代码编写太过于繁琐,所以为了改变这样的繁琐,我将连接数据库的方法进行了一系列的封装,使用户传入一个对象值Object就可以得到想要的. 我在之前写过一篇普通的Java连接MySQL数据库,大家可以看看,以便对比参考之后就知道差距了  数据库--MySQL-->Java篇 接下来我给大家讲讲如何将

通用DAO之MyBatis封装,封装通用的增删改查(二)

曾经发过一篇文章,大概写的就是阿海多么多么厉害,见到某位同事在Hibernate的基础上封装了一下,就以一己之力开发什么什么框架,最后写了个超大的一坨的事. 那么,后续篇来了.阿海不是自负之人,当之前的CRUD框架并没有达到理想的结果时,阿海转向了Mybatis封装.别问我为什么不是Hibernate.我本来就不喜欢Hibernate,即使在之前的一家公司一直被强制性的约束使用Hibernate时,也没有对Hibernate产生什么真正的好感,反而屡次发现了Hibernate的一些问题. 或许是

通用mapper的增删改查方法 留存 备忘

Mybatis通用Mapper介绍与使用 前言 使用Mybatis的开发者,大多数都会遇到一个问题,就是要写大量的SQL在xml文件中,除了特殊的业务逻辑SQL之外,还有大量结构类似的增删改查SQL.而且,当数据库表结构改动时,对应的所有SQL以及实体类都需要更改.这工作量和效率的影响或许就是区别增删改查程序员和真正程序员的屏障.这时,通用Mapper便应运而生-- 什么是通用Mapper 通用Mapper就是为了解决单表增删改查,基于Mybatis的插件.开发人员不需要编写SQL,不需要在DA

mcv实现通用的增删改查

在mvc框架和前一次通用分页的基础上,我们可以完善一下,把它做成一个通用的增删改查 话不多说直接上代码: 先创建一个与数据库表名对应的实体类Book: package com.entity; public class Book { private int bid; private String bname; private float price; @Override public String toString() { return "Book [bid=" + bid + &quo