删除,然后在表上插入数据而不关闭程序并再次运行它

时间:2016-10-27 09:42:11

标签: java mysql sql odbc

我想在删除后直接在mysql数据库上插入数据,我的程序在插入之前检查表上是否有数据,我从表中删除数据,程序运行完美,数据被删除,但是当我想要插入时,消息apppear告诉我该表包含数据!?,它是缓存或处理的东西,!!!? ,你有什么想法

我的代码:

     try {
            String sqll = "Select * from CG1";
            pst = con.prepareStatement(sqll);
            rs = pst.executeQuery();
            // int c = 0;
            while (rs.next()) {
                nam = rs.getString(1);

            }
            System.out.println(nam);
        } catch (SQLException ex) {
            Logger.getLogger(NewJFrame1.class.getName()).log(Level.SEVERE, null, ex);
        }

    //        
        if (nam == null || Integer.parseInt(nam.toString()) == 0) {
            try {

                //   con.setAutoCommit(false);

                pst = con.prepareStatement("insert into CG1(Exe,Mois,Journal)values(?,?,?)");


                for (int i = 0; i < dtm.getRowCount(); i++) {
                    String exe = dtm.getValueAt(i, 0).toString();
                    String mois = dtm.getValueAt(i, 1).toString();
                    String journal = dtm.getValueAt(i, 2).toString();


                    pst.setString(1, exe);
                    pst.setString(2, mois);
                    pst.setString(3, journal);

                    pst.addBatch();


                }
                pst.executeBatch();
                //  con.commit();



            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, e);
            }

        } else {
            if (JOptionPane.showConfirmDialog(null, "Data EXIST,Would You Like TO DeLETE IT !!", "INFO", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                try {
                    pst = con.prepareStatement("delete * from CG1 ");
                    pst.executeUpdate();


                } catch (SQLException ex) {
                    Logger.getLogger(NewJFrame1.class.getName()).log(Level.SEVERE, null, ex);
                }finally{
if(pst!=null){
pst.close();
}
if(rs!=null){
rs.close();
}
if(con!=null){
con.close();
}
}
                JOptionPane.showMessageDialog(rootPane, "DATA DELETED");

            }

        }


        }catch(Exception e){

        }

1 个答案:

答案 0 :(得分:0)

如果要在删除后插入数据,则执行删除后,插入逻辑应位于其他部分。

你应该在不同的方法中使用插入逻辑,如果在DB中没有数据时使用if语句,并在执行删除后在else语句中调用它。