Home Java CRUD Operations in Java using JDBC and MySQL (With Code Examples)

CRUD Operations in Java using JDBC and MySQL (With Code Examples)

12 min read
0
2
34,935

If you are looking for how to develop a Java application that connects with a MySQL database and performs basic operations such as Create, Read, Update, and Delete, then you are in the right place. Here you will learn Java Database Connectivity (JDBC) step by step with examples. We will be using JDBC, Java, and MySQL, which are very popular for use in Java mini projects.

What is CRUD?

CRUD stands for Create, Read, Update, and Delete. These four actions are basic when working with databases. In this project, you’ll build a simple Java application to manage book records in a MySQL database.

What is Java Database Connectivity (JDBC)?

JDBC stands for Java Database Connectivity. It is an application programming interface (API) used for connecting Java programs with databases. It provides methods to query and update data in a database. We’ll be using JDBC to connect our Java program with a MySQL database.

Features of CRUD Project

1.  Insert (Create) new book records

2.  Retrieve (View) all book records

3.  Update (Edit) existing book records

4.  Delete existing unwanted book records

Each book will have the following fields:

Name

Edition

Price

Step-by-Step Guide to Create a Java CRUD Application

Step 1: Download JDK

Make sure you have the Java Development Kit (JDK) installed on your system. Click here to download the latest version.

Step 2: JDBC Download

Download the MySQL JDBC Driver (Connector/J) from the official MySQL website.

Step 3: Create MySQL Database Connection

Create a database in MySQL named javacrud. Create a table book with columns: id, name, edition, and price.

 

we will do the java best practice for understand java programming clearly and easily.

Feature of projects

The system shall be able to record Book details : name,edition,price. The system  shall be able to retrieve the Book details : name,edition,price. Then system shall be able to Edit and Delete the Book details : name,edition,price.

Learn how to make this System Step by step

Step 1: Download JDK  Click here  follow the steps and install it. Step 2: Download an appropriate jdbc driver Click here in order to connect jdbc and mysql. Establish the database connection

Connection con;
PreparedStatement pst;
ResultSet rs;

 public void Connect()
    {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost/javacrud", "root","");
        }
        catch (ClassNotFoundException ex) 
        {
          ex.printStackTrace();
        }
        catch (SQLException ex) 
        {
        	   ex.printStackTrace();
        }

    }

 

AddRecords

you can use the following code snippet to add the records in to database. paste the code inside the add button

public void actionPerformed(ActionEvent e) 
{			
    String bname,edition,price;
    bname = txtbname.getText();
    edition = txtedition.getText();
    price = txtprice.getText();
                
     try {
        pst = con.prepareStatement("insert into book(name,edition,price)values(?,?,?)");
        pst.setString(1, bname);
        pst.setString(2, edition);
        pst.setString(3, price);
        pst.executeUpdate();
        JOptionPane.showMessageDialog(null, "Record Addedddd!!!!!");
        table_load();
                       
        txtbname.setText("");
        txtedition.setText("");
        txtprice.setText("");
        txtbname.requestFocus();
       }

    catch (SQLException e1) 
        {			
       e1.printStackTrace();
    }
}

View Records

you can use the following code snippet to retrieve the data stored in the database and present it to users in a proper format. create a method table_load() .paste the method inside the constructor of the class.when the form is loaded all the records will be shown on the jTable.

public void table_load()
{
	try 
	{
    pst = con.prepareStatement("select * from book");
    rs = pst.executeQuery();
    table.setModel(DbUtils.resultSetToTableModel(rs));
} 
	catch (SQLException e) 
	 {
		e.printStackTrace();
  } 
}

Form Constructor

public JavaCrud() {
    initialize();
    Connect();
    table_load();
}

Search Records 

Enter the book id on textfield relavent book information will be displayed on the relavent textfield. textfield event select as keyReleased event

public void keyReleased(KeyEvent e) {
                
                 try {
                      
                        String id = txtbid.getText();

                            pst = con.prepareStatement("select name,edition,price from book where id = ?");
                            pst.setString(1, id);
                            ResultSet rs = pst.executeQuery();

                        if(rs.next()==true)
                        {
                          
                            String name = rs.getString(1);
                            String edition = rs.getString(2);
                            String price = rs.getString(3);
                            
                            txtbname.setText(name);
                            txtedition.setText(edition);
                            txtprice.setText(price);
    
                        }   
                        else
                        {
                        	txtbname.setText("");
                        	txtedition.setText("");
                            txtprice.setText("");
                             
                        }
                    } 
                
                 catch (SQLException ex) {
                       
                    }
            }

Edit 

you can use the following code snippet to Edit the records.

Paste code inside the Edit button.

                
                
                String bname,edition,price,bid;
                
                
                bname = txtbname.getText();
                edition = txtedition.getText();
                price = txtprice.getText();
                bid  = txtbid.getText();
                
                 try {
                        pst = con.prepareStatement("update book set name= ?,edition=?,price=? where id =?");
                        pst.setString(1, bname);
                        pst.setString(2, edition);
                        pst.setString(3, price);
                        pst.setString(4, bid);
                        pst.executeUpdate();
                        JOptionPane.showMessageDialog(null, "Record Update!!!!!");
                        table_load();
                       
                        txtbname.setText("");
                        txtedition.setText("");
                        txtprice.setText("");
                        txtbname.requestFocus();
                    }

                    catch (SQLException e1) {
                        
                        e1.printStackTrace();
                    }
    
           

Delete

you can use the following code snippet to Delete the records.

Paste code inside the Delete button.

           String bid;
           bid  = txtbid.getText();
           
            try {
                   pst = con.prepareStatement("delete from book where id =?");
           
                   pst.setString(1, bid);
                   pst.executeUpdate();
                   JOptionPane.showMessageDialog(null, "Record Delete!!!!!");
                   table_load();
                  
                   txtbname.setText("");
                   txtedition.setText("");
                   txtprice.setText("");
                   txtbname.requestFocus();
               }

               catch (SQLException e1) {
                   
                   e1.printStackTrace();
               }

What does CRUD in Java stand for?

CRUD in Java refers to the basic operations (Create, Read, Update, Delete) that a Java program performs on a database using JDBC or any database API.

How to 

implement a CRUD in Java?

You can implement a CRUD application in Java using JDBC to communicate with a database like MySQL. Implement SQL statements in Java to insert, read, update, and delete records.

How to deploy Java REST API?

Java REST APIs can be deployed 

with servers like Apache Tomcat or containers like Spring Boot having an embedded web server.

What is CRUD examples?

Some examples of CRUD operations are inserting a new user in a database, reading all the users, updating user data, and deleting a user.

What is API in Java?

Java API is a set of pre-written classes and interfaces that you can invoke to communicate with a service, application, or database.

Is CRUD an API?

CRUD itself is a concept, but it is 

typically implemented as an API (Application Programming Interface) for web or software applications.

This Java JDBC CRUD tutorial gives you the initial know-how to create more complex Java and MySQL projects with good database integration.

 

i have attached the video link below. which will do this tutorials step by step.

  • Java String Methods

    Java provides a rich set of built-in methods for handling String operations efficiently. S…
  • Is Java Hard to Learn?

    Is Java Hard to Learn is it True? Java is one of the most popular programming languages in…
  • How to generate random with weight java

    Generating Random Numbers with Weights in Java Random number generation with weighted prob…
Load More Related Articles
Load More By admin
Load More In Java

Leave a Reply

Your email address will not be published. Required fields are marked *

Check Also

CREATE a Responsive Navigation Bar with FlexBox CSS!

Modern websites must have a navigation bar that is clear and responsive. FlexBox CSS is on…