我非常感谢任何帮助,我已经尝试了各种各样的。
基本上我有一个SQL数据库,我想保存一些数据,我知道如何使用我拥有的所有其他字段,但我也想用这些数据保存当前时间。
str = "INSERT INTO tblResults (username, curTime, outcome) " +
"VALUES(" + "'" + user + "'" +", " + (new Timestamp(date.getTime())) + ", " + "'" + outcome + "'" +")";
然后我执行字符串,这是我多次尝试之一的示例,此尝试编译,但我收到错误:
'16'附近的语法不正确。 保存结果时出错
现在是16小时...我认为它是因为时间戳将时间放在日期之前,而sql则相反,但我不知道如何解决这个问题,所以我很感激任何帮助。感谢
答案 0 :(得分:2)
使用PreparedStatement
,它会为您排序:
final String str = "INSERT INTO tblResults (username, curTime, outcome) VALUES( ?, ?, ?)";
final PreparedStatement preparedStatement = connection.prepareStatement(str);
preparedStatement.setString(1, user);
preparedStatement.setTimestamp(2, new Timestamp(date.getTime()));
preparedStatement.setString(3, outcome);
我猜到了你的其他数据类型......
正如其他人所说,不建议使用Statement
。
答案 1 :(得分:0)
错误即将发生,因为新的Timestamp(date.getTime())的引用值将进入字符串而不是正确的时间戳格式化字符串。
替换为此然后执行: str =“INSERT INTO tblResults(username,curTime,outcome)”+ “VALUES(”+“'”+ user +“'”+“,”+(new Timestamp(date.getTime())。toString()+“,”+“'”+ outcome +“'”+“) “;
如果你没有放入toString()方法,那么对象的引用地址将进入字符串。
您还可以在记录器中打印整个字符串,以查看实际进入str的内容
答案 2 :(得分:0)
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
str = "INSERT INTO tblResults (username, curTime, outcome) " +
"VALUES(" + "'" + user + "'" +", " + dateFormat.format(date) + ", " + "'" + outcome + "'" +")";
答案 3 :(得分:0)
你在SQL查询中错过了新的Timestamp()周围的撇号,但你真的应该使用PreparedStatement代替这种情况。