【问题标题】:Java how to increase the value of doubles in a database tableJava如何增加数据库表中双精度的值
【发布时间】:2018-12-05 22:03:26
【问题描述】:

我在找出将更新我的一个表中的列中的值的查询时遇到了一些麻烦。以下是我的功能:

public void increasePrice(String [] str) {

    PreparedStatement ps = null;
    try {
        ps = connection.prepareStatement("Update Journey Set price+=? where distance <?",PreparedStatement.RETURN_GENERATED_KEYS);
        ps.setDouble(1,Double.parseDouble(str[1]));
        ps.setDouble(2, Double.parseDouble(str[0]));          
        ps.executeUpdate();

        ps.close();
        System.out.println("1 rows updated.");
    } catch (SQLException ex) {
        Logger.getLogger(Jdbc.class.getName()).log(Level.SEVERE, null, ex);
    }
}

为了说明,传入的数组包含距离和价格的值,我想根据距离更新“旅程”表中的价格。例如,如果表中的一条记录的距离(双精度类型)小于给定距离(str[0] 的值),我想将该记录的价格(也是双精度)增加该值'str[1]' 并对表中的所有记录执行此操作。

上面的代码没有给出任何错误,但是数据库中的记录永远不会更新。我真的可以在这方面使用一些帮助,因为我已经搜索了一段时间以尝试找到解决方案但尚未成功。

【问题讨论】:

  • 愚蠢的问题,但你做 connection.commit() - 对吧?
  • @Worthless 是的,我已经实现了,但仍然没有改变
  • 那么,ps.executeUpdate() 的输出是什么?它应该告诉您有多少行受到影响。
  • @Worthless 问题是它不喜欢语法“+”和“
  • 这将导致异常,请发布异常堆栈跟踪。

标签: java sql database sql-update


【解决方案1】:

我不知道您使用的是什么数据库,但我猜是这一行:

ps = connection.prepareStatement("Update Journey Set price+=? where distance <?",PreparedStatement.RETURN_GENERATED_KEYS);

应该这样写:

ps = connection.prepareStatement("Update Journey Set price=price+? where distance <?",PreparedStatement.RETURN_GENERATED_KEYS);

与您的问题无关,但与该行无关

System.out.println("1 rows updated.");

可能会让您在将来浪费数小时的调试时间,因为实际上可以更新 0 行或更多行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-03
    • 2013-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多