Java application to insert null value into a MySQL database?

MySQLMySQLi Database

To set null value with Java, the statement is as follows −

ps.setNull(yourIndex, Types.NULL);

Let us first create a table −

mysql> create table DemoTable1893
   (
   FirstName varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)

The Java code is as follows −

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();
      }
   }
}

This will produce the following output −

Check the MySQL table now using select statement −

mysql> select * from DemoTable1893;

This will produce the following output −

+-----------+
| FirstName |
+-----------+
| NULL      |
+-----------+
1 row in set (0.00 sec)
raja
Published on 27-Dec-2019 06:53:50
Advertisements