java中将date插入mysql中date_Java向MySQL数据库插入时间类型Date数据时需要注意的问题...

MySQL默认的数据类型格式是:yyyy-MM-dd,如:2015-12-30

如下图:

0818b9ca8b590ca3270a3433284dd417.png

因此我们在往MySQL数据库中插入数据时,需要先进行格式化。在java中,我们通常这样格式化日期:

//生成日期对象

Date current_date = new Date();

//设置日期格式化样式为:yyyy-MM-dd

SimpleDateFormat SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

//格式化当前日期

SimpleDateFormat.format(current_date.getTime());

//输出测试一下

System.out.println("当前的系统日期为:" + SimpleDateFormat.format(current_date.getTime()));

运行结果:

0818b9ca8b590ca3270a3433284dd417.png

OK,只要把日期格式转化成 yyyy-MM-dd ,就可以顺利插入到MySQL数据库了。

我用的是SpringMVC+MySQL,下面是controller层和dao层的关键代码:

controller层:

//新生成一个实体对象,把需要插入数据库的数据封装起来

Picture_of_user picture_of_user = new Picture_of_user();

//生成日期对象

Date current_date = new Date();

//设置日期格式化样式为:yyyy-MM-dd

SimpleDateFormat SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

//格式化当前日期

SimpleDateFormat.format(current_date.getTime());

//输出测试一下

System.out.println("当前的系统日期为:" + SimpleDateFormat.format(current_date.getTime()));

picture_of_user.setPicture_name(file.getOriginalFilename());

picture_of_user.setPicture_size((int) file.getSize());

picture_of_user.setUpload_date(SimpleDateFormat.format(current_date.getTime()));

picture_of_user.setPicture_type(file.getContentType());

picture_of_user.setUsername("admin");

//测试输出

System.out.println(SimpleDateFormat.format(current_date.getTime()));

System.out.println("picture_of_user.getPicture_name():" + picture_of_user.getPicture_name());

System.out.println("picture_of_user.getPicture_size():" + picture_of_user.getPicture_size());

System.out.println("picture_of_user.getUpload_date():" + picture_of_user.getUpload_date());

System.out.println("picture_of_user.getPicture_type():" + picture_of_user.getPicture_type());

System.out.println("picture_of_user.getUsername():" + picture_of_user.getUsername());

//调用D层实现类方法,把数据保存到数据库

fileUpload_1_0_Dao.saveUploadPicture(picture_of_user);

dao层关键代码:

@Override

public boolean saveUploadPicture(Picture_of_user picture_of_user) {

//定义一个Boolean类型的flag,用来表示查询状态

boolean flag = false;

sql = "insert into picture_of_user(id,picture_name,picture_size,upload_date,picture_type,username) " +

"values(?,?,?,?,?,?);";

int i = this.getJdbcTemplate().update(sql, new Object[]{

null,

picture_of_user.getPicture_name(),

picture_of_user.getPicture_size(),

picture_of_user.getUpload_date(),

picture_of_user.getPicture_type(),

picture_of_user.getUsername()

});

//如果插入操作执行成功,则flag=true;否则flag=flase

if(i > 0){

//测试输出

System.out.println("i = " + i);

flag = true;

}

else{

//测试输出

System.out.println("i = " + i);

flag = false;

}

return flag;

} 关于java日期格式转化先说到这里。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值