从sql表值中减去scanner值

oprakyz7  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(309)

我试图从表值中减去扫描仪输入。这是我table的截图:

我的代码是这样的:

String url = "jdbc:mysql://localhost:3306/Project";
    String username = "x";
    String password = "y";

    try {
        Scanner scanner = new Scanner(System.in);

        System.out.println("What would you like to buy?");
        int purchase_id = scanner.nextInt();

        System.out.println("How many would you like to purchase?");
        int quantity = scanner.nextInt();

        Connection conn = DriverManager.getConnection(url, username, password);
        Statement myStmt = conn.createStatement();

        String sql = "update seattleBranch set inventory = " + quantity + "where item_id = 001";

        myStmt = conn.prepareStatement(sql);

        ((PreparedStatement) myStmt).executeUpdate();
    }

    catch (SQLException e) {
        e.printStackTrace();
    }
}

我的代码的输出是:

java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'item_id = 001' at line 1
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1092)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1040)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1347)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1025)
    at branchComms.main(branchComms.java:27)

以下是我希望我的表减去100(我的扫描仪输入量)后的样子:

我不确定为什么减去我的扫描器变量(数量)不工作,我将感谢任何更正我的代码。

yeotifhr

yeotifhr1#

查询中缺少 where 部分,应该是这样的:

String sql = "update seattleBranch set inventory = " + quantity + " where item_id = 001";

相关问题