java怎么将指定时间添加到数据库

1509
2023/11/27 10:27:54
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

要将指定时间添加到数据库,你需要使用JDBC(Java数据库连接)来连接到数据库并执行相应操作。
以下是一个示例代码,演示如何将指定时间添加到数据库中:

import java.sql.*;
public class InsertTimeToDatabase {

????public?static?void?main(String[]?args)?{

????????//?数据库连接信息

????????String?url?=?“jdbc:mysql://localhost:3306/mydatabase”;

????????String?username?=?“root”;

????????String?password?=?“password”;

????????Connection?conn?=?null;

????????PreparedStatement?pstmt?=?null;

????????try?{

????????????//?连接数据库

????????????conn?=?DriverManager.getConnection(url,?username,?password);

????????????//?SQL插入语句

????????????String?sql?=?“INSERT?INTO?mytable?(time_column)?VALUES?(?)”;

????????????//?创建PreparedStatement对象

????????????pstmt?=?conn.prepareStatement(sql);

????????????//?指定时间

????????????java.util.Date?date?=?new?java.util.Date();

????????????java.sql.Timestamp?timestamp?=?new?java.sql.Timestamp(date.getTime());

????????????//?设置参数

????????????pstmt.setTimestamp(1,?timestamp);

????????????//?执行插入操作

????????????int?rows?=?pstmt.executeUpdate();

????????????if?(rows?>?0)?{

????????????????System.out.println(“时间已成功插入到数据库中!”);

????????????}

????????}?catch?(SQLException?e)?{

????????????e.printStackTrace();

????????}?finally?{

????????????//?关闭连接和释放资源

????????????try?{

????????????????if?(pstmt?!=?null)?{

????????????????????pstmt.close();

????????????????}

????????????????if?(conn?!=?null)?{

????????????????????conn.close();

????????????????}

????????????}?catch?(SQLException?e)?{

????????????????e.printStackTrace();

????????????}

????????}

????} }

你需要将示例代码中的urlusernamepassword修改为你自己数据库的连接信息,并根据你的表结构修改SQL插入语句中的表名和列名。
然后,使用setTimestamp方法将指定时间设置为参数,并执行插入操作。如果插入成功,将输出"时间已成功插入到数据库中!"。
请注意,这只是示例代码,实际应用中你可能需要处理异常、关闭连接和释放资源等。另外,确保你已经导入了正确的JDBC驱动程序。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: java匿名函数的应用场景有哪些