简体   繁体   English

使用准备好的语句进行JDBC更新

[英]JDBC update using prepared statement

I am trying to update a table using Java JDBC. 我正在尝试使用Java JDBC更新表。 The method I am using does not throw any errors but the table is not updating. 我使用的方法不会引发任何错误,但是表没有更新。 The create table method is below: 创建表方法如下:

public static void Table()
      {
        Connection c = null;
        Statement stmt = null;
        try {
          Class.forName("org.sqlite.JDBC");
          c = DriverManager.getConnection("jdbc:sqlite:WalkerTechCars.db");
          System.out.println("Opened database successfully");

          stmt = c.createStatement();
          String sql = "CREATE TABLE IF NOT EXISTS CUSTOMERS2 " +
                       "(PHONE TEXT PRIMARY KEY     NOT NULL," +
                       " SURNAME            TEXT    NOT NULL, " + 
                       " FIRSTNAME          TEXT     NOT NULL, " + 
                       " HOME               TEXT, " + 
                       " ADDRESS            TEXT, " + 
                       " POSTCODE           Text)"; 
          stmt.executeUpdate(sql);
          stmt.close();
          c.close();
        } catch ( Exception e ) {
          System.err.println( e.getClass().getName() + ": " + e.getMessage() );
          System.exit(0);
        }
        System.out.println("Customers2 created successfully");
      }

The update method is below: 更新方法如下:

public static void updateCustomers()
      {
        Connection c = null;
        PreparedStatement pstmt = null;
        try {
          Class.forName("org.sqlite.JDBC");
          c = DriverManager.getConnection("jdbc:sqlite:WalkerTechCars.db");
          c.setAutoCommit(false);
          System.out.println("Opened database successfully");

          String query = "UPDATE CUSTOMERS2 set ADDRESS = ? where PHONE = ? ";
          pstmt = c.prepareStatement(query); // create a statement
          pstmt.setString(1, "1"); // set input parameter 1
          pstmt.setString(2, "DOES THIS WORK"); // set input parameter 2
          pstmt.executeUpdate(); // execute update statement

          pstmt.close();
          c.close();
        } catch ( Exception e ) {
          System.err.println( e.getClass().getName() + ": " + e.getMessage() );
          System.exit(0);
        }
        System.out.println("Update Completed successfully HELLO");
      }

I have tried to find some clear instructions on this but cant find any. 我试图找到一些明确的说明,但是找不到任何说明。 I do not really understand JDBC and prepared statement very well 我不太了解JDBC和准备好的语句

When autoCommit is false ( c.setAutoCommit(false); ), you must manually commit the transaction... 如果autoCommitfalsec.setAutoCommit(false); ),则必须手动提交事务。

Add... 加...

c.commit()

After pstmt.executeUpdate(); pstmt.executeUpdate();

You code also has a flaw, in that if some kind of error occurs during the preparation or execution of the statement, both the Connection and PreparedStatement could be left open, causing a resource leak 您的代码还存在一个缺陷,即如果在准备或执行语句期间发生某种错误,则ConnectionPreparedStatement都可能保持打开状态,从而导致资源泄漏

If you're using Java 7+ you can use the try-with-resources feature, for example... 如果您使用的是Java 7+,则可以使用try-with-resources功能,例如...

try {
    Class.forName("org.sqlite.JDBC");
    try (Connection c = DriverManager.getConnection("jdbc:sqlite:WalkerTechCars.db")) {
        c.setAutoCommit(false);
        System.out.println("Opened database successfully");

        String query = "UPDATE CUSTOMERS2 set ADDRESS = ? where PHONE = ? ";
        try (PreparedStatement pstmt = c.prepareStatement(query)) {
            pstmt.setString(1, "1"); // set input parameter 1
            pstmt.setString(2, "DOES THIS WORK"); // set input parameter 2
            pstmt.executeUpdate(); // execute update statement
            c.commit();
        }

    } catch (SQLException exp) {
        exp.printStackTrace();
    }
} catch (ClassNotFoundException exp) {
    exp.printStackTrace();
    System.out.println("Failed to load driver");
}

This will ensure that regardless of how you leave the try block the resource will be closed. 这将确保无论您如何离开try块,资源都将被关闭。

You might also consider taking a look at the JDBC(TM) Database Access 您还可以考虑看看JDBC(TM)数据库访问

Your update method will set ADDRESS to 1 if there is any row in table with PHONE = does this work. 如果表中有PHONE =的任何行,则您的更新方法会将ADDRESS设置为1。

Try to put Address in 1st Input parameter and Phone 2nd Input parameter 尝试将地址输入第一输入参数和电话第二输入参数

When a connection is created, it is in auto-commit mode. 创建连接后,它处于自动提交模式。 We need to use [setAutoCommit] method only when we need to make Auto Commit false and make it manual commit after executing the query. 仅在需要将Auto Commit设置为false并在执行查询后使其手动提交时,才需要使用[setAutoCommit]方法。

More details at Oracle site on JDBC Transaction . 在Oracle网站上有关JDBC Transaction的更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM