【问题标题】:How to delete data from sql in netbeans如何在netbeans中从sql中删除数据
【发布时间】:2015-12-11 09:30:13
【问题描述】:

我想添加一个删除按钮,当用户单击表中的数据并单击删除时,数据将被删除。如何添加删除按钮的代码?我必须在删除按钮下或其他任何地方添加任何内容吗?

package Warehouse;
import java.sql.*;
import java.util.Vector; 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
/**
 *
 * @author sarah
 */
public class Pallet extends javax.swing.JFrame {
private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver";
	private static final String DB_CONNECTION = "jdbc:oracle:thin:@localhost:1521:XE";
	private static final String DB_USER = "SARAH";
	private static final String DB_PASSWORD = "12345";
    /**
     * Creates new form Pallet
     */
    public Pallet() {
        initComponents();
        Vector<Vector<String>> data;
Vector<String> header;
data = getPallet();
header = new Vector<String>();
header.add("Pallet ID");

header.add("Quantity");


PaTable.setModel(new javax.swing.table.DefaultTableModel(data,
header));        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        palletid = new javax.swing.JLabel();
        qtty = new javax.swing.JLabel();
        PalletText = new javax.swing.JTextField();
        QttyText = new javax.swing.JTextField();
        addbutton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        PaTable = new javax.swing.JTable();
        exitbutton = new javax.swing.JButton();
        delete = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Pallet");

        palletid.setText("Pallet ID");

        qtty.setText("Quantity");

        addbutton.setText("Add");
        addbutton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addbuttonActionPerformed(evt);
            }
        });

        PaTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null}
            },
            new String [] {
                "Pallet", "Quantity"
            }
        ));
        jScrollPane1.setViewportView(PaTable);

        exitbutton.setText("Exit");
        exitbutton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitbuttonActionPerformed(evt);
            }
        });

        delete.setText("Delete");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 31, Short.MAX_VALUE)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 357, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(143, 143, 143)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(59, 59, 59)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(qtty)
                            .addComponent(palletid))
                        .addGap(86, 86, 86)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(PalletText, javax.swing.GroupLayout.DEFAULT_SIZE, 68, Short.MAX_VALUE)
                            .addComponent(QttyText))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(exitbutton, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(addbutton, javax.swing.GroupLayout.Alignment.TRAILING))))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(delete)
                .addGap(32, 32, 32))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(palletid)
                    .addComponent(PalletText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(addbutton))
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(qtty)
                    .addComponent(QttyText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(exitbutton))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 186, Short.MAX_VALUE)
                .addGap(54, 54, 54)
                .addComponent(delete)
                .addGap(21, 21, 21))
        );

        pack();
    }// </editor-fold>                        

    private void addbuttonActionPerformed(java.awt.event.ActionEvent evt) {                                          
       try {
        // TODO add your handling code here:
        insertRecordIntoTable();
        JFrame parent = new JFrame();
        JOptionPane.showMessageDialog(parent, "Record is added.");
    } catch (SQLException ex) {
        Logger.getLogger(SubPallet.class.getName()).log(Level.SEVERE, null, ex);
    } // TODO add your handling code here:
    }                                         

    private void exitbuttonActionPerformed(java.awt.event.ActionEvent evt) {                                           
       setVisible (false);
        InterfaceMenu form = new InterfaceMenu();
        form.setVisible(true); // TODO add your handling code here:
    }                                          

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Pallet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Pallet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Pallet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Pallet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Pallet().setVisible(true);
            }
        });
    }
private Vector getPallet(){
 Vector<Vector<String>> palletVector = new Vector<Vector<String>>();

 try{
 DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
 Connection con;
 con = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:XE", "SARAH", "12345");
 Statement stmt = con.createStatement();
 ResultSet rset = stmt.executeQuery("SELECT * FROM PALLET");
 while (rset.next()){
 Vector<String> pallet = new Vector<String>();
 pallet.add(rset.getString(1)); 
 pallet.add(rset.getString(2)); 
 ;
 
 palletVector.add(pallet);
 }
 con.close();
 stmt.close();
 }
 catch (Exception e){
 System.out.print(e.getMessage());
 }
 return palletVector;
}
    // Variables declaration - do not modify                     
    private javax.swing.JTable PaTable;
    private javax.swing.JTextField PalletText;
    private javax.swing.JTextField QttyText;
    private javax.swing.JButton addbutton;
    private javax.swing.JButton delete;
    private javax.swing.JButton exitbutton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel palletid;
    private javax.swing.JLabel qtty;
    // End of variables declaration                   

    private void insertRecordIntoTable() throws SQLException {
        Connection dbConnection = null;
        PreparedStatement preparedStatement = null;
        String query="insert into PALLET (PALLET_ID,QTTY_IN_PALLET) values(?,?)";
        
        
        try {
            dbConnection = getDBConnection();
            preparedStatement = dbConnection.prepareStatement(query);
            
            preparedStatement.setInt(1, Integer.parseInt(PalletText.getText()));
     preparedStatement.setInt(2, Integer.parseInt(QttyText.getText()));
            
            
            // execute insert SQL stetement
            preparedStatement.executeUpdate();
            
            System.out.println("Record is inserted !");
        } 
        catch (SQLException e) {System.out.println(e.getMessage());} 
        finally {
            if (preparedStatement != null) {
                preparedStatement.close();
            }
            
            if (dbConnection != null) {
                dbConnection.close();
            }
        }

    }
    
    private Connection getDBConnection() {
        
        Connection dbConnection = null;
        try {Class.forName(DB_DRIVER);} 
        catch (ClassNotFoundException e){System.out.println(e.getMessage());}
        
        try{
            dbConnection = DriverManager.getConnection(
                    DB_CONNECTION, DB_USER,DB_PASSWORD);
            return dbConnection;
        }
        catch (SQLException e){System.out.println(e.getMessage());}
        
        return dbConnection;
    }
}

【问题讨论】:

    标签: java sql jdbc netbeans


    【解决方案1】:

    在您的initComponents 中您将编码

    delete.setText("Delete");
    delete.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            deletebuttonActionPerformed(evt)("Delete");
        }
    });
    

    这个方法会从 PALLET 表中删除 所有项目

    private void deletebuttonActionPerformed(java.awt.event.ActionEvent evt) {                                           
         try(Connection con = getDBConnection();
            PreparedStatemet ps = con.prepareStatement("DELETE FROM PALLET")) {
             int numDeleted = ps.executeUpdate();
             System.out.println(""+numDeleted + " items were removed from PALLET");
         }
    }  
    

    如果您只需要删除单行,则需要添加WHERE 条件。

    protected void deletePallet(int palletId) {
        try (Connection con = getDBConnection();
                PreparedStatemet ps = con.prepareStatement("DELETE FROM PALLET WHERE PALLET_ID = ?")) {
            ps.setInt(1, palletId);
            int numDeleted = ps.executeUpdate();
            System.out.println("" + numDeleted + " items were removed from PALLET");
        }
    }
    

    现在剩下的唯一任务就是获取当前选定行的 ID - 您知道该怎么做 ,不是吗?

    【讨论】:

      猜你喜欢
      • 2012-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多