MySQL NOW() equivalent in Java for prepared statements

If you are used to MySQL then you probably know the MySQL function NOW() which inserts the current date and time in a MySQL query. But if you use JDBC and prepared statements, then you can reconstruct this function with a GregorianCalendar (which is the successor of Date):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public void insertArticle(Article article) throws SQLException
{
  //query = "INSERT INTO articles(title,content,date) VALUES (?,?,NOW())";
  query = "INSERT INTO articles(title,content,date) VALUES (?,?,?)";
 
  statement = connection.prepareStatement(query);
 
  statement.setString(1, article.getTitle());
  statement.setString(2, article.getContent());
  statement.setTimestamp(3, new Timestamp(new GregorianCalendar().getTimeInMillis()));
 
  logger.info(statement);
  statement.executeUpdate();
}

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.