插入时间戳时在Java服务器中获取Postgres错误
我在Spring boot平台上操作,并连接到Postgres数据库。尝试执行插入时,出现以下错误:插入时间戳时在Java服务器中获取Postgres错误,java,postgresql,jdbc,error-handling,timestamp,Java,Postgresql,Jdbc,Error Handling,Timestamp,我在Spring boot平台上操作,并连接到Postgres数据库。尝试执行插入时,出现以下错误: Database error: org.postgresql.util.PSQLException: ERROR: syntax error at or near "19" Position: 110 我正在执行代码插入,如下所示: @RequestMapping(value="/event", method=RequestMethod.POST) public @ResponseBody S
Database error: org.postgresql.util.PSQLException: ERROR: syntax error at or near "19" Position: 110
我正在执行代码插入,如下所示:
@RequestMapping(value="/event", method=RequestMethod.POST)
public @ResponseBody
String uploadEvent(@RequestParam("title") String title,
@RequestParam("description") String description,
@RequestParam("start") Date start,
@RequestParam("end") Date end){
// Schema
/*
StartTime timestamp NOT NULL,
EndTime timestamp NOT NULL,
Description varchar(1500),
name varchar(80) NOT NULL,
DisplayPicLoc varchar(80),
attendenceCount int
*/
Timestamp startTime = null;
Timestamp endTime = null;
try{
startTime = new Timestamp(start.getTime());
endTime = new Timestamp(end.getTime());
}
catch(Exception e){
System.err.print("Date conversion error: " + e);
return "failure";
}
System.out.println("Event received with Title: " + title +
" Description: " + description +
" Start: " + startTime +
" End: " + endTime);
Connection connection = DatabaseConnection.connection;
if(connection==null){
new DatabaseConnection();
}
try{
connection.setAutoCommit(false);
Statement preparedStatement = connection.createStatement();
String query = "INSERT INTO event " +
"(StartTime, EndTime, Description, name, DisplayPicLoc, attendenceCount) " +
"VALUES (" + startTime +
", " + endTime +
", " + description +
", " + title +
", null" +
", 0);";
preparedStatement.executeUpdate(query);
return "success";
}
catch(Exception e){
System.err.println("Database error: " + e);
return "failure";
}
我正在尝试将具有以下值的事件插入数据库:
Event received with Title: a Description: a Start: 2016-03-02 19:00:00.0 End: 2016-03-03 19:00:00.0
出现此错误的原因是什么?您使用的
PreparedStatement
是错误的。您正在将这些值连接到查询字符串中。您应该使用占位符和PreparedStatement.setTimestamp()
和PreparedStatement.setString()
。请阅读详细信息,谢谢。您的评论实际上修复了我的错误:D