Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Insert Null Value into MySQL Database using Java



In this program, we will connect to a MySQL database and insert a null value into a table using Java's JDBC API. We will use the PreparedStatement class along with the setNull() method to achieve this. After the value is inserted, you can check the table to see how the null value is reflected.

Steps to insert null value into a MySQL database

Following are the steps to insert null value into a MySQL database ?

  • Establish a connection to the MySQL database using the DriverManager.getConnection() method.
  • Define the SQL query that inserts a value into the table DemoTable1893.
  • Prepare the statement using con.prepareStatement().
  • Use ps.setNull(1, Types.NULL) to set a null value for the first column.
  • Execute the update using ps.executeUpdate().
  • Print a message indicating the operation's completion.
  • Optionally, check the database using a SELECT statement to confirm the insertion.

Java program to insert null value into a MySQL database

Below is the Java program to insert null value into a MySQL database ?

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Types;
public class InsertNullValueIntoDatabase{
   public static void main(String[] args){
      Connection con=null;
      PreparedStatement ps=null;
      try{
         con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/web?useSSL=false",
"root","123456");
         String query="insert into DemoTable1893(FirstName) values(?) ";
         ps= con.prepareStatement(query);      
         ps.setNull(1, Types.NULL);
         ps.executeUpdate();
         System.out.println("Check the DemoTable1893 ");
      }
      catch(Exception e){
        e.printStackTrace();
      }
   }
}

Check the MySQL table now using the select statement ?

mysql> select * from DemoTable1893;

Output

+-----------+
| FirstName |
+-----------+
| NULL        |
+-----------+
1 row in set (0.00 sec)
Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2024-10-10T11:36:15+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements