Java在NetBeans中查看/编辑/创建/删除MySQL数据库表中的数据

vmpqdwk3  于 2022-11-10  发布在  Java
关注(0)|答案(1)|浏览(261)

编辑:我正在编辑我的问题,因为我在网上找到了一个不同的教程,我已经比以前进步了,但我仍然有问题。
我正在尝试创建一个应用程序,以便在NetBeans中查看,编辑,创建或删除MySQL数据库表中的数据。
我正在遵循这个教程:https://www.youtube.com/watch?v=6PvKTg9NXkU
当我单击“查看”按钮时,表单出现,数据库表中的数据出现。当我单击“删除”按钮时,它从数据库表中删除一行,当我单击“添加”按钮时,一个条目被添加到我的数据库表中。但是我的“更新”按钮不起作用。它应该允许我编辑数据库表中预先存在的条目。但是我得到的只是一个对话框窗口,上面写着"更新了,但实际上没有。
有人知道我做错了什么吗?我不明白我怎么能遵循教程,可以有不同的结果。
StoreDB.java 代码

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package storedatabase;

import javax.swing.JOptionPane;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import javax.swing.table.DefaultTableModel;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Jade
 */
public class StoreDB extends javax.swing.JFrame {

private static final String username = "ctuonline";
private static final String password = "student";
private static final String database = "jdbc:mysql://localhost:3306/store";

Connection sqlCon = null;
PreparedStatement pst = null;
ResultSet rs = null;
int q, i, id, deleteItem;

    public StoreDB() {
        initComponents();
    }

    /**
     * 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.
     */

   public void upDateDB()
   {
       try
       {
           Class.forName("com.mysql.jdbc.Driver");
           sqlCon = DriverManager.getConnection(database,username,password);
           pst = sqlCon.prepareStatement("select * from customers");

           rs = pst.executeQuery();
           ResultSetMetaData stData = rs.getMetaData();

           q = stData.getColumnCount();

           DefaultTableModel RecordTable = (DefaultTableModel)customerTable.getModel();
           RecordTable.setRowCount(0);

           while(rs.next())
           {
               Vector columnData = new Vector();

               for (i = 1; i <= q; i++)
               {
                   columnData.add(rs.getString("customerID"));
                   columnData.add(rs.getString("customerName"));
                   columnData.add(rs.getString("customerAddress"));
                   columnData.add(rs.getString("customerCity"));
                   columnData.add(rs.getString("customerState"));
                   columnData.add(rs.getString("customerZip"));

               }
               RecordTable.addRow(columnData);
           }

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

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        zipLabel = new javax.swing.JLabel();
        idLabel = new javax.swing.JLabel();
        nameLabel = new javax.swing.JLabel();
        addressLabel = new javax.swing.JLabel();
        cityLabel = new javax.swing.JLabel();
        stateLabel = new javax.swing.JLabel();
        zipField = new javax.swing.JTextField();
        idField = new javax.swing.JTextField();
        nameField = new javax.swing.JTextField();
        addressField = new javax.swing.JTextField();
        cityField = new javax.swing.JTextField();
        stateField = new javax.swing.JTextField();
        deleteButton = new javax.swing.JButton();
        updateButton = new javax.swing.JButton();
        viewButton = new javax.swing.JButton();
        addButton = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        customerTable = new javax.swing.JTable();
        jPanel8 = new javax.swing.JPanel();
        headerLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jPanel2.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        zipLabel.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
        zipLabel.setText("Zip:");
        jPanel2.add(zipLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 170, 70, 20));

        idLabel.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
        idLabel.setText("ID:");
        jPanel2.add(idLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 20, 70, 20));

        nameLabel.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
        nameLabel.setText("Name:");
        jPanel2.add(nameLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(19, 50, 70, 20));

        addressLabel.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
        addressLabel.setText("Address:");
        jPanel2.add(addressLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 80, 70, 20));

        cityLabel.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
        cityLabel.setText("City:");
        jPanel2.add(cityLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 110, 70, 20));

        stateLabel.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
        stateLabel.setText("State:");
        jPanel2.add(stateLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 140, 70, 20));

        zipField.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
        jPanel2.add(zipField, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 170, 120, -1));

        idField.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
        jPanel2.add(idField, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 20, 120, -1));

        nameField.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
        jPanel2.add(nameField, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 50, 120, -1));

        addressField.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
        jPanel2.add(addressField, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 80, 120, -1));

        cityField.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
        jPanel2.add(cityField, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 110, 120, -1));

        stateField.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
        jPanel2.add(stateField, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 140, 120, -1));

        deleteButton.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
        deleteButton.setText("Delete");
        deleteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteButtonActionPerformed(evt);
            }
        });
        jPanel2.add(deleteButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 260, 90, -1));

        updateButton.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
        updateButton.setText("Update");
        updateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updateButtonActionPerformed(evt);
            }
        });
        jPanel2.add(updateButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 260, 90, -1));

        viewButton.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
        viewButton.setText("View");
        viewButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                viewButtonActionPerformed(evt);
            }
        });
        jPanel2.add(viewButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 220, 90, -1));

        addButton.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
        addButton.setText("Add");
        addButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addButtonActionPerformed(evt);
            }
        });
        jPanel2.add(addButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 220, 90, -1));

        jPanel1.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 100, 240, 320));

        jPanel4.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        jPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        customerTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Name", "Address", "City", "State", "Zip"
            }
        ));
        customerTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                customerTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(customerTable);

        jPanel4.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 620, 300));

        jPanel1.add(jPanel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 100, 640, 320));

        jPanel8.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        jPanel8.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        headerLabel.setFont(new java.awt.Font("Verdana", 1, 36)); // NOI18N
        headerLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        headerLabel.setText("Store Database Table Customers");
        jPanel8.add(headerLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 10, 850, 50));

        jPanel1.add(jPanel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 20, 890, 70));

        getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 930, 440));

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

    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             

        DefaultTableModel RecordTable = (DefaultTableModel)customerTable.getModel();
        int SelectedRows = customerTable.getSelectedRow();

        try
        {
            id = Integer.parseInt(RecordTable.getValueAt(SelectedRows, 0).toString());

            deleteItem = JOptionPane.showConfirmDialog(null, "Confirm Delete?", "Warning", JOptionPane.YES_NO_OPTION);
            if (deleteItem == JOptionPane.YES_OPTION)
            {
                Class.forName("com.mysql.jdbc.Driver");
                sqlCon = DriverManager.getConnection(database, username, password);
                pst = sqlCon.prepareStatement("delete from customers where customerID = ?");

                pst.setInt(1, id);
                pst.executeUpdate();
                JOptionPane.showMessageDialog(this, "Record Updated");
                upDateDB();

                idField.setText("");
                idField.requestFocus();
                nameField.setText("");
                addressField.setText("");
                cityField.setText("");
                stateField.setText("");
                zipField.setText("");

            }
        } catch (ClassNotFoundException ex) {
        Logger.getLogger(StoreDB.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(StoreDB.class.getName()).log(Level.SEVERE, null, ex);
    }

    }                                            

    private void updateButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             

        DefaultTableModel RecordTable = (DefaultTableModel)customerTable.getModel();
        int SelectedRows = customerTable.getSelectedRow();

        try 
        {
            id = Integer.parseInt(RecordTable.getValueAt(SelectedRows, 0).toString());
            Class.forName("com.mysql.jdbc.Driver");
            sqlCon = DriverManager.getConnection(database, username, password);
            pst = sqlCon.prepareStatement("update customers set customerName = ?, customerAddress = ?, customerCity = ?, customerState = ?,  customerZip = ? where (customerID = ?)");

            pst.setString(1, idField.getText());
            pst.setString(2, nameField.getText());
            pst.setString(3, addressField.getText());
            pst.setString(4, cityField.getText());
            pst.setString(5, stateField.getText());
            pst.setString(6, zipField.getText());

            pst.executeUpdate();
            JOptionPane.showMessageDialog(this, "Record Updated");
            upDateDB();
        } catch (SQLException ex) {
            Logger.getLogger(StoreDB.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(StoreDB.class.getName()).log(Level.SEVERE, null, ex);
        }

    }                                            

    private void viewButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           

        upDateDB();
    }                                          

    private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          

        try 
        {
            Class.forName("com.mysql.jdbc.Driver");
            sqlCon = DriverManager.getConnection(database, username, password);
            pst = sqlCon.prepareStatement("insert into customers(customerID,customerName,customerAddress,customerCity,customerState,customerZip) value(?,?,?,?,?,?)");

            pst.setString(1, idField.getText());
            pst.setString(2, nameField.getText());
            pst.setString(3, addressField.getText());
            pst.setString(4, cityField.getText());
            pst.setString(5, stateField.getText());
            pst.setString(6, zipField.getText());

            pst.executeUpdate();
            JOptionPane.showMessageDialog(this, "Record Added");
            upDateDB();
        } catch (SQLException ex) { 
        Logger.getLogger(StoreDB.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(StoreDB.class.getName()).log(Level.SEVERE, null, ex);
    } 

    }                                         

    private void customerTableMouseClicked(java.awt.event.MouseEvent evt) {                                           

        DefaultTableModel RecordTable = (DefaultTableModel) customerTable.getModel();
        int SelectedRows = customerTable.getSelectedRow();

        idField.setText(RecordTable.getValueAt(SelectedRows, 0).toString());
        nameField.setText(RecordTable.getValueAt(SelectedRows, 1).toString());
        addressField.setText(RecordTable.getValueAt(SelectedRows, 2).toString());
        cityField.setText(RecordTable.getValueAt(SelectedRows, 3).toString());
        stateField.setText(RecordTable.getValueAt(SelectedRows, 4).toString());
        zipField.setText(RecordTable.getValueAt(SelectedRows, 5).toString());

    }                                          

    /**
     * @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(StoreDB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(StoreDB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(StoreDB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(StoreDB.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 StoreDB().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton addButton;
    private javax.swing.JTextField addressField;
    private javax.swing.JLabel addressLabel;
    private javax.swing.JTextField cityField;
    private javax.swing.JLabel cityLabel;
    private javax.swing.JTable customerTable;
    private javax.swing.JButton deleteButton;
    private javax.swing.JLabel headerLabel;
    private javax.swing.JTextField idField;
    private javax.swing.JLabel idLabel;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField nameField;
    private javax.swing.JLabel nameLabel;
    private javax.swing.JTextField stateField;
    private javax.swing.JLabel stateLabel;
    private javax.swing.JButton updateButton;
    private javax.swing.JButton viewButton;
    private javax.swing.JTextField zipField;
    private javax.swing.JLabel zipLabel;
    // End of variables declaration                   
}

NetBeans输出

ant -f C:\\Users\\jades\\Desktop\\Java\\StoreDatabase -Dnb.internal.action.name=run.single -Djavac.includes=storedatabase/StoreDB.java -Drun.class=storedatabase.StoreDB run-single
init:
Deleting: C:\Users\jades\Desktop\Java\StoreDatabase\build\built-jar.properties
deps-jar:
Updating property file: C:\Users\jades\Desktop\Java\StoreDatabase\build\built-jar.properties
Compiling 1 source file to C:\Users\jades\Desktop\Java\StoreDatabase\build\classes
Note: C:\Users\jades\Desktop\Java\StoreDatabase\src\storedatabase\StoreDB.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
compile-single:
run-single:
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
BUILD SUCCESSFUL (total time: 23 seconds)

MySQL database table

wr98u20j

wr98u20j1#

您可以尝试在getCustomerList()方法中更改String查询。
请尝试以下操作:字符串查询=“SELECT * FROM customers“;
它工作原因是,您在连接数据库mysql://localhost:3306/store中调用了表“store. store. customers”,并复制了表“store.store.customers”

相关问题