将 Java.sql.Date 插入 Derby 数据库
我正在尝试将日期对象插入数据库,但它说我正在尝试插入整数。这是我的代码:
public void insertAssignment(long studentId, String newAssignment, int ptsTotal, int ptsRecieved, String category, Date dueDate, String term, int yr) {
java.sql.Date temp = new java.sql.Date(dueDate.getTime());
try{
s.execute("INSERT INTO Assignments " +
"VALUES (" + studentId + ",'" + newAssignment + "'," + ptsTotal +
"," + ptsRecieved + ",'" + category + "'," + temp
+ ",'" + term + "'," + yr + ")");
System.out.println("Assignment inserted.");
}
catch(SQLException error){
System.err.println("Unable to insertAssignment.");
error.printStackTrace(System.err);
System.exit(0);
}
}
我的错误: java.sql.SQLSyntaxErrorException:“DATE”类型的列不能保存“INTEGER”类型的值。
I am trying to insert a date object into the database but it says im trying to insert an Integer. Here is my code:
public void insertAssignment(long studentId, String newAssignment, int ptsTotal, int ptsRecieved, String category, Date dueDate, String term, int yr) {
java.sql.Date temp = new java.sql.Date(dueDate.getTime());
try{
s.execute("INSERT INTO Assignments " +
"VALUES (" + studentId + ",'" + newAssignment + "'," + ptsTotal +
"," + ptsRecieved + ",'" + category + "'," + temp
+ ",'" + term + "'," + yr + ")");
System.out.println("Assignment inserted.");
}
catch(SQLException error){
System.err.println("Unable to insertAssignment.");
error.printStackTrace(System.err);
System.exit(0);
}
}
My error:
java.sql.SQLSyntaxErrorException: Columns of type 'DATE' cannot hold values of type 'INTEGER'.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为此,请改用准备好的语句并使用 setter。
目前,您将日期展平为字符串值(需要采用正确的格式才能使数据库正常工作),并丢失它是一个日期,因此数据库需要解析它。您可以使用准备好的语句来避免这种情况。
To do this, use a prepared statement instead and use a setter.
Currently you flatten your date to a string value (which needs to be in the right format for the database for this to work) and lose that it is a date so the database needs to parse it. You avoid this using the prepared statement.