zoukankan      html  css  js  c++  java
  • 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);
            
        }        
  • 相关阅读:
    UIAutomation识别UI元素
    pycharm调试bug Process finished with exit code 1073740791 (0xC0000409)
    adb常用命令
    win10 安装Pytorch GPU版+CUDA+cuDNN
    AD 端口相关
    sqlserver数据库排序规则
    sqlserver数据库备份的存储过程
    专有软件不是唯一!试试54款开源服务器软件[转]
    AD管理维护与排错工具
    LDAP over SSL (LDAPS) Certificate
  • 原文地址:https://www.cnblogs.com/133261c/p/9317169.html
Copyright © 2011-2022 走看看