您的位置:首页 > 数据库

字符串存入数据库date类型字段

2017-07-25 16:39 543 查看
有时候为了计算方便等原因需要将时间以date格式存入数据库,但是前台传过来的数据类型都是字符串,如果将字符串直接插入date类型的字段中会抛:
ORA-01861: 文字与格式字符串不匹配


前台页面有一个表单,如下所示:

<form action="......" method="get">
<input type="date" name="date">
<input type="submit" value="提交">
</form>


提交表单时传到后台只是选定日期对应的字符串表示形式:

如选定:



由浏览提地址栏可知传到后台只是字符串的”2017-07-25”,

http://localhost:8080/....../save.do?date=2017-07-25


这样直接保存到数据库中就会抛如下异常:

org.springframework.dao.DataIntegrityViolationException: PreparedStatementCallback; SQL [INSERT INTO DEMO (DATATEST) VALUES  (?)]; ORA-01861: 文字与格式字符串不匹配
; nested exception is java.sql.SQLDataException: ORA-01861: 文字与格式字符串不匹配


数据库结构如下:



解决办法:

1、使用注解:

@DateTimeFormat
@JsonFormat


在实体类代表日期字段的get方法上添加注解:

import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

public class DateModel {
private Date date;

@DateTimeFormat(pattern = "yyyy-MM-dd")
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
public Date getDate() {
return date;
}

public void setDate(Date date) {
this.date = date;
}

@Override
public String toString() {
return "DateModel{" +
"date='" + date + '\'' +
'}';
}
}


dao层:(此处使用jdbctemplate)

import com.srie.ylb.model.DateModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;

@Repository
public class DateDao {

@Autowired
private JdbcTemplate jdbcTemplate;

public void saveDate(DateModel dateModel) {
String sql = "INSERT INTO DEMO (DATATEST) VALUES  (:date)";
NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate);
SqlParameterSource sqlParameterSource = new BeanPropertySqlParameterSource(dateModel);
namedParameterJdbcTemplate.update(sql, sqlParameterSource);
}
}


2、使用Java将代表日期的字符串转换为java.util.date再插入数据库

使用SimpleDateFormat:

@RequestMapping("/save")
public void saveDate(String dateStr) throws ParseException {
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
dateDao.saveDate(date);
}


也可使用java.util.Calendar,只不过麻烦些。

dao层:

public void saveDate(Date date) {
String sql = "INSERT INTO DEMO (DATATEST) VALUES  (?)";
jdbcTemplate.update(sql, date);
}


3、使用数据库函数TO_CHAR()函数

dao层:

public void saveDate(String date) {
String sql = "INSERT INTO DEMO (DATATEST) VALUES (TO_DATE(?, 'yyyy-MM-dd'))";
j
4000
dbcTemplate.update(sql, date);
}


测试结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐