字符串存入數據庫date類型字段

有時候爲了計算方便等原因需要將時間以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'))";
    jdbcTemplate.update(sql, date);
}

測試結果:


這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章