数据库时间字段类型是datetime在java中怎么获取当前时间存入数据这个字段中
可以使用Java中的java.sql.Timestamp类来获取当前时间并存入数据库中的datetime字段中。
示例代码:
import java.sql.Timestamp;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.DriverManager;
public class Example {
public static void main(String[] args) {
try {
// 连接数据库
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
// 获取当前时间
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
// 插入数据
String sql = "INSERT INTO mytable (datetime_column) VALUES (?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setTimestamp(1, timestamp);
pstmt.executeUpdate();
// 关闭连接
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
在上面的代码中,我们首先连接数据库,然后使用java.sql.Timestamp类获取当前时间,最后将时间存入数据库中的datetime字段中。注意,我们使用PreparedStatement类的setTimestamp()方法将时间值设置到SQL语句中的占位符中。最后,记得关闭连接
原文地址: https://www.cveoy.top/t/topic/dnAy 著作权归作者所有。请勿转载和采集!