How to Insert Records Using to a Mysql Database using PreparedStatement :

Below code are two class that work together to add records to a MySQL Database using PreparedStatement. Before coding below code make s...

How to Insert Records Using to a Mysql Database using PreparedStatement :
Below code are two class that work together to add records to a MySQL Database using PreparedStatement.
Before coding below code make sure you know how to How to connect to the mysql database in java

JFrame class with a form where the user enters the details.


  1. AddItems Class

import DbConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import javax.swing.JOptionPane;

/**
 *
 * @author acer
 */
public class AddItems extends javax.swing.JFrame {
    private DbConnection dbConnection;
public int itemId,packet_Number;
public String itemName,itemCategory,itemDescription;
    /**
     * Creates new form AddItems
     */
    public AddItems() {
        initComponents();
        setTitle("Add New Items");
        setLocationRelativeTo(null);
        setVisible(true);
    }

    /**
     * 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")
    //                           
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        fiieldItemId = new javax.swing.JTextField();
        fieldItemName = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        fieldCategory = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        fieldPackets = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        fieldDescription = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(AddItems.class, "AddItems.jLabel1.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(AddItems.class, "AddItems.jLabel2.text")); // NOI18N

        fiieldItemId.setText(org.openide.util.NbBundle.getMessage(AddItems.class, "AddItems.fiieldItemId.text")); // NOI18N

        fieldItemName.setText(org.openide.util.NbBundle.getMessage(AddItems.class, "AddItems.fieldItemName.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel3, org.openide.util.NbBundle.getMessage(AddItems.class, "AddItems.jLabel3.text")); // NOI18N

        fieldCategory.setText(org.openide.util.NbBundle.getMessage(AddItems.class, "AddItems.fieldCategory.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel4, org.openide.util.NbBundle.getMessage(AddItems.class, "AddItems.jLabel4.text")); // NOI18N

        fieldPackets.setText(org.openide.util.NbBundle.getMessage(AddItems.class, "AddItems.fieldPackets.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel5, org.openide.util.NbBundle.getMessage(AddItems.class, "AddItems.jLabel5.text")); // NOI18N

        fieldDescription.setText(org.openide.util.NbBundle.getMessage(AddItems.class, "AddItems.fieldDescription.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jButton1, org.openide.util.NbBundle.getMessage(AddItems.class, "AddItems.jButton1.text")); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jButton2, org.openide.util.NbBundle.getMessage(AddItems.class, "AddItems.jButton2.text")); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jButton3, org.openide.util.NbBundle.getMessage(AddItems.class, "AddItems.jButton3.text")); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(fieldCategory, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addGap(18, 18, 18)
                                .addComponent(fieldDescription, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(53, 53, 53))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(41, 41, 41)
                        .addComponent(fiieldItemId, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel4))
                .addGap(50, 50, 50)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(fieldItemName)
                    .addComponent(fieldPackets, javax.swing.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(120, Short.MAX_VALUE)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(61, 61, 61)
                .addComponent(jButton3)
                .addGap(51, 51, 51)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(189, 189, 189))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(fiieldItemId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(fieldItemName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(fieldCategory, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(fieldPackets, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(31, 31, 31)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(fieldDescription, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(51, 51, 51)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(67, Short.MAX_VALUE))
        );

        pack();
    }//                         

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
this.dispose();
        // TODO add your handling code here:
    }                                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
try{
        addItem();

}
catch(Exception e){e.printStackTrace();}
        // TODO add your handling code here:
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //
        /* 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(AddItems.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AddItems.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AddItems.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AddItems.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AddItems().setVisible(true);
            }
        });
    }
//methods
    
    public void addItem()  throws Exception
    {
     PreparedStatement pstmt = null;
       dbConnection=new DbConnection();
       Connection con = dbConnection.dbConnect();
   try{
 itemId=Integer.parseInt(fiieldItemId.getText());
 packet_Number=Integer.parseInt(fieldPackets.getText());
    itemName= fieldItemName.getText();
      itemName=fieldItemName.getText();
      itemCategory=fieldCategory.getText();
      itemDescription=fieldDescription.getText();
    
}
catch(NumberFormatException e)
{
}
        if(itemId==0)
    {
    JOptionPane.showMessageDialog(this, "Please enter Item Id", "Input required",JOptionPane.INFORMATION_MESSAGE);    
    }
    else if(itemName .isEmpty())
    {
    JOptionPane.showMessageDialog(this, "Please enter Item Name", "Input required",JOptionPane.INFORMATION_MESSAGE);    
    } 
        
        else
    {
        try {
   
    String query = "insert into products(item_id, item_name, item_category,number_of_items,item_description)"
            + " values(?, ?, ?,?,?)"; 
        
    
         pstmt = con.prepareStatement(query); // create a statement
      pstmt.setInt(1, itemId); // set input parameter 1
      pstmt.setString(2, itemName); // set input parameter 2
      pstmt.setString(3,  itemCategory); // set input parameter 3
      pstmt.setInt(4, packet_Number);
       pstmt.setString(5, itemDescription); 
      
      
      
      pstmt.executeUpdate(); 
JOptionPane.showMessageDialog(this, "Item added successfully", "Items ",JOptionPane.INFORMATION_MESSAGE);    
// execute insert statement
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      pstmt.close();
      con.close();
      
    }
    
    }}
    
    
    
    
    // Variables declaration - do not modify                     
    private javax.swing.JTextField fieldCategory;
    private javax.swing.JTextField fieldDescription;
    private javax.swing.JTextField fieldItemName;
    private javax.swing.JTextField fieldPackets;
    private javax.swing.JTextField fiieldItemId;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    // End of variables declaration     
   public static void main(String[] args)
 {

new AddItems();

}


              
}



  1. Database connection class

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;
public class DbConnection {
  public Connection con;
public Connection dbConnect(){  
try
{
Class.forName("com.mysql.jdbc.Driver"); 
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/pointofsale","root","");

return con;
}
catch(Exception e)
{
   JOptionPane.showMessageDialog(null, "Cannot connect to database", " Database Connection",JOptionPane.ERROR_MESSAGE);

}
return con;
}


}


Database Design
Create a database and name it as "pointofsale"

Go ahead and create table "products" with below design.
How to Insert Records Using to a Mysql Database using PreparedStatement :


COMMENTS

Name

android android Apps android emulators antivirus blogger bluestack Break Statement in Java constructors download downloader drivers emulators java java control statements java do-while loop java for loop java infinitive do-while loop java system methods java tutorials Java While Loop java.awt java.swing javalookandfeel javascript JButton JCheckBox JColorChooser JComboBox JDialog JFileChooser JFrame JLayeredPane JList JMenuBar joomla JOptionPane JPanel JPasswordField JPopupMenu JProgressBar JRadioButton JScrollBar JSlider JSpinner JTabbedPane JTable JTextArea JTextField JToolBar mysql php plugins Polymorphism setToolTiptext skype for windows software swing class themes Visual Studio Code WeChat whatsapp wordpress
false
ltr
item
Java Codes: How to Insert Records Using to a Mysql Database using PreparedStatement :
How to Insert Records Using to a Mysql Database using PreparedStatement :
https://1.bp.blogspot.com/-aQz6mC6AtMs/WaMwEDNilWI/AAAAAAAAIig/0MTDnPQ1EmUMh8SFFPgSnh7ofeALzoq6wCLcBGAs/s320/form_design-min.PNG
https://1.bp.blogspot.com/-aQz6mC6AtMs/WaMwEDNilWI/AAAAAAAAIig/0MTDnPQ1EmUMh8SFFPgSnh7ofeALzoq6wCLcBGAs/s72-c/form_design-min.PNG
Java Codes
http://www.download-all.net/2017/08/how-to-insert-records-using-to-mysql.html
http://www.download-all.net/
http://www.download-all.net/
http://www.download-all.net/2017/08/how-to-insert-records-using-to-mysql.html
true
7826648292785071009
UTF-8
Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS CONTENT IS PREMIUM Please share to unlock Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy