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?
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.
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.
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().
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.
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()); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With