mysql给所有的表创建触发器

从网上复制的一份JDBCUtils

public class JDBCUtils {
    /**
     * 获取连接方法
     *
     * @return
     */
    public static Connection getConnection() {
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:32123/kass", "root", "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 释放资源方法
     * @param conn
     * @param pstmt
     * @param rs
     */
    public static void release(Connection conn, PreparedStatement pstmt, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

在数据库中添加一个用来记录的表

DROP TABLE IF EXISTS `triggertable`;
CREATE TABLE `triggertable` (
  `time` datetime NOT NULL,
  `tableName` varchar(255) DEFAULT NULL,
  `optype` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

批量增加触发器的代码

public class trigger {

    //获取所有的表名
    private List<String> getAllTable( ){
        List<String> resultList = new ArrayList<>();

        Connection conn = null;
        PreparedStatement pstmt  = null;
        ResultSet rs = null;
        try {
            //1、获取连接
            conn = JDBCUtils.getConnection();
            //2、获取预执行对象
            String sql = "show TABLES";
            pstmt = conn.prepareStatement(sql);

            //4、执行查询或者执行操作
            rs = pstmt.executeQuery();
            while(rs.next()){
                resultList.add( rs.getString("Tables_in_kass") );
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            //5、释放资源
            JDBCUtils.release(conn, pstmt, rs);
        }
        //关闭数据库连接资源
        return resultList;
    }

    //批量删除触发器
    @Test
    public void delRiggerbatch(){

    }





    //批量执行触发器
    @Test
    public void excuterRiggerSql(){
        List<String> allTable = getAllTable();
        if(allTable==null || allTable.size()<=0)
            return;
        if(allTable.contains("triggertable")){
            allTable.remove("triggertable");
        }
        //构建触发器语句 并执行触发器语句
        List<String> triggerInsertSqlList = buildInsertTriggerSql(allTable);

        triggerInsertSqlList.forEach(item-> System.out.println(item));

        if( triggerInsertSqlList!=null && triggerInsertSqlList.size()>0 ){
            triggerInsertSqlList.forEach(itemSql->{
                excuterRiggerSql(itemSql);
            });
        }
        List<String> triggerUpdateSqlList = buildUpdateTriggerSql(allTable);
        if( triggerUpdateSqlList!=null && triggerUpdateSqlList.size()>0 ){
            triggerUpdateSqlList.forEach(itemSql->{
                excuterRiggerSql(itemSql);
            });
        }

        List<String> triggerDeleteSqlList = buildDeleteTriggerSql(allTable);
        if(triggerDeleteSqlList!=null && triggerDeleteSqlList.size()>0){
            triggerDeleteSqlList.forEach(itemSql->{
                excuterRiggerSql(itemSql);
            });
        }
    }

    //执行一个触发器
    public void excuterRiggerSql( String sql ){
        Connection conn = null;
        PreparedStatement pstmt  = null;
        ResultSet rs = null;
        try {
            //执行触发器语句
            conn = JDBCUtils.getConnection();
            //2、获取预执行对象
            pstmt = conn.prepareStatement(sql);
            //4、执行查询或者执行操作
            pstmt.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //5、释放资源
            JDBCUtils.release(conn, pstmt, rs);
        }
    }




    public List<String> buildInsertTriggerSql( List<String> allTable ){
        if( allTable==null && allTable.size()<=0 ){
            return null;
        }
        List<String> resultList = new ArrayList<>();
        allTable.stream().forEach(item->{
            String triggerInserSql = "CREATE DEFINER=`root`@`localhost` TRIGGER `insert_"+item+"` BEFORE INSERT ON "+item+" FOR EACH ROW INSERT INTO triggertable (time, tableName, optype) VALUES (now(), '"+item+"', 'insert');";
            resultList.add(triggerInserSql);
        });
        return resultList;
    }


    public List<String> buildUpdateTriggerSql( List<String> allTable ){
        if( allTable==null && allTable.size()<=0 ){
            return null;
        }
        List<String> resultList = new ArrayList<>();
        allTable.stream().forEach(item->{
            String triggerUpdateSql = "CREATE DEFINER=`root`@`localhost` TRIGGER `update_"+item+"` BEFORE UPDATE ON "+item+" FOR EACH ROW INSERT INTO triggertable (time, tableName, optype) VALUES (now(), '"+item+"', 'update');";
            resultList.add(triggerUpdateSql);
        });
        return resultList;
    }

    public List<String> buildDeleteTriggerSql( List<String> allTable ){
        if( allTable==null && allTable.size()<=0 ){
            return null;
        }
        List<String> resultList = new ArrayList<>();
        allTable.stream().forEach(item->{
            String triggerDeleteSql = "CREATE DEFINER=`root`@`localhost` TRIGGER `delete_"+item+"` BEFORE DELETE ON "+item+" FOR EACH ROW INSERT INTO triggertable (time, tableName, optype) VALUES (now(), '"+item+"', 'delete');";
            resultList.add(triggerDeleteSql);
        });
        return resultList;
    }
}

没有批量删除,采用备份数据库的方式,大量的创建连接对象,以及销毁连接对象.不知道能不能有更好的方式,
小心MySQLIntegrityConstraintViolationException的意思是违反了数据库的完整性约束,用来记录的表的主键一定不能重复

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值