MySql主從表的主表刪除資料

來源:互聯網
上載者:User

標籤:nbsp   stream   mit   rtt   dao   start   cat   man   manager   

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);            }        

 

MySql主從表的主表刪除資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.