1

I am trying to insert some rows using a prepare-bind statement. One of the columns is of type TIMESTAMP. How do I bind the variable for this column with the current epoch time?

I have the following table:

CREATE TABLE orders {
  user_id TEXT,
  order_time TIMESTAMP,
  order_id UUID DEFAULT gen_random_uuid(),
  order_details TEXT,
  PRIMARY KEY (user_id, order_time DESC, order_id),
  FOREIGN KEY (user_id) REFERENCES %s (user_id)
);

I have the following prepare statement code:

String stmt = "INSERT INTO orders " +
              "(user_id, order_time, order_details) " + 
              "VALUES (?, ?, ?);"
PreparedStatement p = connection.prepareStatement(stmt);

Now I am trying to bind the current epoch time System.currentTimeMillis() to variable 2 in this statement. How should I do that?

1 Answers1

1

The corresponding Java type to your SQL's TIMESTAMP is most likely java.sql.Timestamp. You can generate a current timestamp using:

Timestamp timestamp = new Timestamp(System.currentTimeMillis());

So, your prepared statement code might look like:

String stmt = "INSERT INTO orders " +
              "(user_id, order_time, order_details) " + 
              "VALUES (?, ?, ?);"
PreparedStatement p = connection.prepareStatement(stmt);
p.setString(1, "Karthik");
p.setTimestamp(2, new Timestamp(System.currentTimeMillis()));
p.setString(3, "here is some order text");
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360