小编典典

数据截断:错误的日期时间值:“

mysql

谁能通过示例JSP代码帮助我,以通过JDBC在MySql数据库中存储日期?当我尝试执行下面给出的代码时,出现以下异常:

com.mysql.jdbc.MysqlDataTruncation:数据截断:不正确的datetime值:第1行的’date’列的’‘

如何克服这个问题?以下是我的代码:

Connection con = null;

String StaffName = request.getParameter("StaffName");
// String subcode = request.getParameter("subcode");
String hourId = request.getParameter("hourId");
if (hourId == null)
    hourId = "";
String day = request.getParameter("day");
if (day == null)
    day = "";
String date = request.getParameter("date");
try {
    Class.forName("com.mysql.jdbc.Driver");
    con = DriverManager.getConnection("jdbc:mysql://localhost:3306/StaffAllocation", "root", "success");

    // PreparedStatement stat = con.PrepareStatement();
    String updateString = "INSERT INTO tblstaffallocation (StaffName,hourId,daysId,date) VALUES (?,?,?,?)";
    PreparedStatement preparedStatement = con.prepareStatement(updateString);

    preparedStatement.setString(1, StaffName);
    preparedStatement.setInt(2, 0);
    preparedStatement.setInt(3, 0);
    preparedStatement.setString(4, date);
} catch (Exception e) {
    out.print(e);
}

阅读 630

收藏
2020-05-17

共1个答案

小编典典

要将日期设置为准备好的语句,您需要更改值的类型:

String date = request.getParameter("date");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); // your template here
java.util.Date dateStr = formatter.parse(date);
java.sql.Date dateDB = new java.sql.Date(dateStr.getTime());

现在将String date转换为java.sql.Date并使用另一种方法:

preparedStatement.setDate(4,dateDB);
2020-05-17