Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set current date and time using prepared statement?

I have a column in database having datatype DATETIME. I want to set this column value to current date and time using `PreparedStatement. How do I do that?

like image 286
Param-Ganak Avatar asked Oct 02 '11 11:10

Param-Ganak


People also ask

Can we use PreparedStatement for update query?

The Statement. executeUpdate method works if you update data server tables with constant values. However, updates often need to involve passing values in variables to the tables. To do that, you use the PreparedStatement.

When we use PreparedStatement execute update?

executeUpdate. Executes the SQL statement in this PreparedStatement object, which must be an SQL Data Manipulation Language (DML) statement, such as INSERT , UPDATE or DELETE ; or an SQL statement that returns nothing, such as a DDL statement.

How do you execute a PreparedStatement?

Once you have created the PreparedStatement object you can execute it using one of the execute() methods of the PreparedStatement interface namely, execute(), executeUpdate() and, executeQuery().


2 Answers

Use PreparedStatement#setTimestamp() wherein you pass a java.sql.Timestamp which is constructed with System#currentTimeMillis().

preparedStatement.setTimestamp(index, new Timestamp(System.currentTimeMillis())); // ... 

Alternativaly, if the DB supports it, you could also call a DB specific function to set it with the current timestamp. For example MySQL supports now() for this. E.g.

String sql = "INSERT INTO user (email, creationdate) VALUES (?, now())"; 

Or if the DB supports it, change the field type to one which automatically sets the insert/update timestamp, such as TIMESTAMP instead of DATETIME in MySQL.

like image 174
BalusC Avatar answered Sep 19 '22 15:09

BalusC


conn = getConnection(); String query = "insert into your_table(id, date_column) values(?, ?)"; pstmt = conn.prepareStatement(query); pstmt.setString(1, "0001"); java.sql.Date date = getCurrentDatetime(); pstmt.setDate(2, date); 

Where the function getCurrentDatetime() does the following:

public java.sql.Date getCurrentDatetime() {     java.util.Date today = new java.util.Date();     return new java.sql.Date(today.getTime()); } 
like image 24
kinkee Avatar answered Sep 22 '22 15:09

kinkee