使用预准备语句和用户输入更新数据

时间:2016-08-14 16:29:07

标签: java jdbc prepared-statement

我需要你的帮助。我不知道为什么我的代码没有更新数据,尽管我使用了正确的代码和正确的数据输入。我希望你能帮助我。这是我的任务。谢谢!

是的,这是我的代码:

包裹分配;

if
    statement 2;
else
    statement 3;

输出截图:
enter image description here

1 个答案:

答案 0 :(得分:2)

你颠倒了参数:

Update studentrecord set lastname = ? where studentid = ?
                                    ↑                   ↑
                                    1                   2

但你写道:

preparedStatement2.setInt(1, studentid);
preparedStatement2.setString(2, lastname);

应该是:

preparedStatement2.setString(1, lastname);
preparedStatement2.setInt(2, studentid);

除此之外,您应该将JDBC代码与用户提示代码隔离开来,并且您应该使用try-with-resources,因为您当前正在泄漏资源(非常糟糕)。

private static void updateTable() {
    try {
        Scanner scan =new Scanner(System.in);
        System.out.println("Updating...");
        System.out.println("Enter StudentId: ");
        int studentid=scan.nextInt();
        System.out.println("Enter Lastname: ");
        String lastname=scan.next();

        try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentdatabase", "root", "password")) {
            updateTable(conn, studentid, lastname);
            listRecords(conn);
        }
    } catch(Exception exc){
        exc.printStackTrace();
    }
}
private static void updateTable(Connection conn, int studentid, String lastname) throws SQLException {
    String updateSQL = "UPDATE studentrecord SET lastname = ? WHERE studentid = ?";
    try (PreparedStatement stmt = conn.prepareStatement(updateSQL)) {
        stmt.setString(1, lastname);
        stmt.setInt(2, studentid);
        stmt.executeUpdate();
    }
}
private static void listRecords(Connection conn) throws SQLException {
    String selectSQL = "SELECT * FROM studentrecord";
    try (
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(selectSQL)
    ) {
        while (rs.next()) {
            System.out.println(rs.getInt("studentid") + " " +
                               rs.getString("lastname") + " " +
                               rs.getString("firstname") + " " +
                               rs.getInt("tfee") + " " +
                               rs.getDouble("fee_per_unit") + " " +
                               rs.getInt("total_unit") + " " +
                               rs.getString("year") + " " +
                               rs.getString("course") + " " +
                               rs.getString("section"));
        }
    }
}