 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java application to insert null value into a MySQL database
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)
Advertisements
 