You are currently viewing Inserting values to MySQL database – Java Swing

Inserting values to MySQL database – Java Swing

Hello guys, Bushan here, welcome back to B2 Tech! Today in this article, we will discuss how to insert values into MySQL database with the help of Java! We will achieve this using Java Swings!



In the previous article, we have created an empty JFrame form so I will make use of same JFrame form. Let’s design JFrame form like this,



So the goal is to insert the values into a database as soon as we click the Insert button, so we have to write a code inside the button. Every component has its own event, we will create an ActionPerformed Event for the Insert button. To create an event double click on the button, it will create an ActionPerformed Event. Let’s write the below code,

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try{
            String sql = "insert into details(sid, sname, sage) values(?, ?, ?)";
            pst = conn.prepareStatement(sql);
            pst.setString(1, txt_id.getText());
            pst.setString(2, txt_name.getText());
            pst.setString(3, txt_age.getText());
            pst.execute();
            JOptionPane.showMessageDialog(null, "Inserted successfully!");
        }catch(Exception e){
            JOptionPane.showMessageDialog(null, e);
        }
    }



At this point, if you run the application you will see the below form, try to insert values into a database

Here is the complete code,

import java.sql.*;
import javax.swing.*;
public class login extends javax.swing.JFrame {
    Connection conn = null;
    PreparedStatement pst = null;
    public login() {
        initComponents();
        conn = connection.connectdb();
    }
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try{
            String sql = "insert into details(sid, sname, sage) values(?, ?, ?)";
            pst = conn.prepareStatement(sql);
            pst.setString(1, txt_id.getText());
            pst.setString(2, txt_name.getText());
            pst.setString(3, txt_age.getText());
            pst.execute();
            JOptionPane.showMessageDialog(null, "Inserted successfully!");
        }catch(Exception e){
            JOptionPane.showMessageDialog(null, e);
        }
    }
}



That’s it for this article, I hope this article helped you in one or the other way, do let me know about this article in the comment section down below if you like the content share with your friends and I will see you in the next article.

 

Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

Leave a Reply