Inserting a value with type datetime in a column using JDBC

This example assumes that you have set up a table orders.

orders looks like this:

mysql> desc orders;
+-----------+------------+------+-----+---------+----------------+
| Field     | Type       | Null | Key | Default | Extra          |
+-----------+------------+------+-----+---------+----------------+
| orderid   | int(10)    |      | PRI | NULL    | auto_increment |
| custid    | int(10)    | YES  | MUL | NULL    |                |
| timestamp | datetime   | YES  |     | NULL    |                |
| status    | tinyint(4) | YES  |     | NULL    |                |
+-----------+------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

The following example will populate this table with 4 rows, date is passed in as a java.util.Date and converted to a java.sql.Timestamp.

Main.java:

import java.util.*;
import java.text.*;
import java.sql.*;
  
public class Main {
   public static void main(String []args) throws Exception {
      try {
         Class.forName("org.gjt.mm.mysql.Driver").newInstance();
         Connection conn = DriverManager.getConnection("jdbc:mysql://192.168.0.1/esus", 
                                                       "joris",
                                                       "mypass");
 
         Statement stmt = conn.createStatement();
         DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
         createOrder(stmt, 1, new java.util.Date(), 0);
         createOrder(stmt, 1, df.parse("12/12/1972"), 1);
         createOrder(stmt, 1, df.parse("2/1/1999"), 2);
         createOrder(stmt, 2, df.parse("5/01/2001"), 0);
         stmt.close();
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   } 
 
   public static void createOrder(Statement stmt, 
                                  int custid, java.util.Date timestamp, int status) 
                                           throws SQLException, ParseException {
      java.sql.Timestamp sqlDateTime = new java.sql.Timestamp(timestamp.getTime());
      stmt.executeUpdate("INSERT INTO orders (custid, timestamp, status) " + 
                         "VALUES (" + custid + ", '" +
                                  sqlDateTime + "', " + status + ")");

   }
}

This is the result:

mysql> select * from orders;
+---------+--------+---------------------+--------+
| orderid | custid | timestamp           | status |
+---------+--------+---------------------+--------+
|       1 |      1 | 2001-10-13 17:33:11 |      0 | 
|       2 |      1 | 1972-12-12 00:00:00 |      1 | 
|       3 |      1 | 1999-02-01 00:00:00 |      2 | 
|       4 |      2 | 2001-05-01 00:00:00 |      0 | 
+---------+--------+---------------------+--------+
4 rows in set (0.00 sec)