简体   繁体   English

如何使用jsp在mysql数据库中插入当前日期?

[英]how to insert current date in mysql database using jsp?

I am trying to insert the date using this code: 我正在尝试使用以下代码插入日期:

java.sql.Timestamp sqlNow=new java.sql.Timestamp(new java.util.Date().getTime());
pstTimestamp(1,sqlNow);

On running the code, the result is successful, but the date is not been displayed in the database. 运行代码时,结果成功,但是日期未显示在数据库中。

You should use PreparedStatement and use it to set the date as follows :- 您应该使用PreparedStatement并使用它来设置date ,如下所示:

PreparedStatement pstmt = con.prepareStatement("INSERT INTO table_name (col_name) VALUES (?)");
pstmt.setTimestamp(1, new java.sql.Timestamp(new java.util.Date().getTime()));
pstmt.executeUpdate();

Read more here 在这里阅读更多

Try this 尝试这个

PreparedStatement ps = con.prepareStatement("INSERT INTO table_name (col_name) VALUES (now())");
ps.executeUpdate();

use now() so that it will get the date in db format only. 使用now()使其仅以db格式获取日期。

Make sure you commit after running the command. 确保在运行命令后提交。 Or make sure auto commit is enabled on the connection. 或确保在连接上启用了自动提交。

Just you need to provide the java.sql.Timestamp class object to the PreparedStatement object rest of work will be done by driver. 只需要向PreparedStatement对象提供java.sql.Timestamp类对象,其余工作将由驱动程序完成。 I think there is a problem in your code while setting place holder's value(parameter). 我认为在设置占位符的值(参数)时代码中存在问题。 Use pstmnt.setTimestamp(int index, java.sql.Timestamp timestamp_object); 使用pstmnt.setTimestamp(int index, java.sql.Timestamp timestamp_object); now execute your query as: pstmnt.executeUpdate(); 现在以以下方式执行查询:pstmnt.executeUpdate();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM