MySql主从表的主表删除数据

1.第一种:

解除主从表的约束关键

一般来说,在我们给主表添加外键时,切记要设计“外键名称”,以便于日后可以删除外键约束。

  声明外键约束语法:

alter table 从表名 add [constraint] [外键名称] foreign key(从表中的外键字段名) references 主表(主表的主键);

  删除外键约束:

alter table 从表名 drop foreign key 外键名称;

2.第二种:

先删除从表中与主表有关系的数据,再删除主表中的数据(具体自己操作)。

       //1.开启事务
            DataSourceUtils.startTransaction();

            //2.更新商品 把从表中与主表中有关系的数据度删除
            ProductDao pd=(ProductDao) BeanFactory.getBean("ProductDao");
            pd.updateCid(cid);
            
            //3.删除分类 才能对主表进行删除
            CategoryDao cd=(CategoryDao) BeanFactory.getBean("CategoryDao");
            cd.delete(cid);
            
            //4.事务控制
            DataSourceUtils.commitAndClose();
            
            //5.清空缓存
            CacheManager cm = CacheManager.create(CategoryServiceImpl.class.getClassLoader().getResourceAsStream("ehcache.xml"));
            Cache cache = cm.getCache("categoryCache");
            cache.remove("clist");

  updateCid方法为: 

    /**
     * 更新商品的cid 为删除分类的时候准备
     */
    @Override
    public void updateCid(String cid) throws Exception {
        QueryRunner qr = new QueryRunner();
        //把要删除的从表中的数据的外键置为与主表中无关的数据
        String sql="update product set cid = null where cid = ?";
        qr.update(DataSourceUtils.getConnection(), sql, cid);
    }

  cd.delete(cid)方法为:

    /**
     * 删除分类
     */
    @Override
    public void delete(String cid) throws Exception {
        QueryRunner qr = new QueryRunner();
        String sql="delete from category where cid = ?";
        qr.update(DataSourceUtils.getConnection(), sql, cid);
        
    }        

猜你喜欢

转载自www.cnblogs.com/133261c/p/9317169.html