如何使用Java在MySQL中插入日期和时间

In this example I will show you the simplest way to insert date and time in MySQL database using Java.

在此示例中,我将向您展示使用Java在MySQL数据库中插入日期和时间的最简单方法。

This example is for inserting current date and time. You can parse any date and time to insert. Below are the steps to do this.

本示例用于插入当前日期和时间 。 您可以解析任何要插入的日期和时间。 以下是执行此操作的步骤。

How to Insert Date and Time in MySQL Using Java

如何使用Java在MySQL中插入日期和时间

1. First establish connection with MySQL database.

1.首先建立与MySQL数据库的连接。

2. Now create an object of java.utl.Date class.

2.现在创建一个java.utl.Date类的对象。

3. After that create objects of java.sql.Date and java.sql.Timestamp. There constructor will take object of java.util.Date class as an argument. The getTime() method is used to get current date or time.

3.之后,创建java.sql.Datejava.sql.Timestamp的对象。 那里的构造函数将java.util.Date类的对象作为参数。 getTime()方法用于获取当前日期或时间。

4. The java.sql.Date class is used for date and java.sql.Timestamp is used for storing time.

4. java.sql.Date类用于日期,而java.sql.Timestamp用于存储时间。

5. Now prepare a statement with insert query.

5.现在准备一个带有插入查询的语句。

6. The setDate() method is used to set date while setTimestamp() is used to set time.

6. setDate()方法用于设置日期,而setTimestamp()用于设置时间。

7. Finally execute the query by executeUpdate() method to insert the date and time in database.

7.最后通过executeUpdate()方法执行查询,以在数据库中插入日期和时间。

Below I have shared an example for this.

下面我分享了一个例子。

Example

package com;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
 
public class DateTimeExample {
	public static void main(String args[]){
		try{
			Class.forName("com.mysql.jdbc.Driver");
			Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/demo","root","root");
			
			java.util.Date date=new java.util.Date();
			
			java.sql.Date sqlDate=new java.sql.Date(date.getTime());
			java.sql.Timestamp sqlTime=new java.sql.Timestamp(date.getTime());
			
			PreparedStatement ps=con.prepareStatement("insert into record (date,time) values(?,?)");
			ps.setDate(1,sqlDate);
			ps.setTimestamp(2,sqlTime);
			ps.executeUpdate();			
			
			ps.close();
			con.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}

After adding the record the table will look like.

添加记录后,表将如下所示。

How to Insert Date and Time in MySQL Using Java

Comment below if you have any doubts related to above tutorial.

如果您对以上教程有任何疑问,请在下面评论。

翻译自: https://www.thecrazyprogrammer.com/2016/02/how-to-insert-date-and-time-in-mysql-using-java.html

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值