有时候为了计算方便等原因需要将时间以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); }
使用数据库函数TO_CHAR()函数 dao层:
public void saveDate(String date) { String sql = "INSERT INTO DEMO (DATATEST) VALUES (TO_DATE(?, 'yyyy-MM-dd'))"; jdbcTemplate.update(sql, date); } 测试结果:
原文:https://blog.csdn.net/wangxiaoan1234/article/details/76084176 版权声明:本文为博主原创文章,转载请附上博文链接!
