gpt4 book ai didi

java - 数据截断 : Incorrect datetime value: ''

转载 作者:IT王子 更新时间:2023-10-29 00:37:13 25 4
gpt4 key购买 nike

任何人都可以帮助我提供示例 JSP 代码以通过 JDBC 将日期存储在 MySql 数据库中吗?当我尝试执行下面给出的代码时,出现以下异常:

com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: '' for column 'date' at row 1

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

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);
}

最佳答案

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

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);

关于java - 数据截断 : Incorrect datetime value: '' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20088808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com