Add some months to current date using Java with MySQL?

MySQLMySQLi Database

Following is the syntax to add months using INTERVAL with Java − MySQL.

String query;
query = "insert into yourTableName values(curdate()+interval howManyNumberOfMonths month)";

Following is the current date −

mysql> select curdate();
| curdate()  |
| 2020-10-25 |
1 row in set (0.00 sec)

Let us create a table −

mysql> create table demo12
−> (
−> created_date date
−> );
Query OK, 0 rows affected (1.84 sec)

Here, I am going to add 2 months to the current date from Java. Now, date will be inserted into the table 2020−12−25.

The Java code is as follows


import java.sql.Connection;
import java.sql.DriverManager;
import com.mysql.jdbc.Statement;
public class AddSomeMonthDemo {
   public static void main(String[] args) {
      Connection con = null;
      Statement statement = null;
      try {
         con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sampledatabase", "root", "123456");
         statement = (Statement) con.createStatement();
         String query;
         query = "insert into demo12 values(curdate()+interval 2 month)";
         int status = statement.executeUpdate(query);
         if (status > 0)
            System.out.println("Record inserted succesfully..Look into the database");
            System.out.println("Error not inserted");
         } catch (Exception e) {

This will produce the following output −

Now you can verify whether the data inserted in the table by displaying all the records. Following is the query −

Updated on 19-Nov-2020 11:15:54