来自JDBC ResultSet的更新程序方法的意外惊喜(?)

问题描述 投票:-1回答:1

我们正在通过JDBC访问的MySQL数据库中有一些数据。根据从数据库中读取的值,我们希望在代码中播放一些“技巧”。我阅读了有关ResultSet的更新程序方法的文档,并很高兴发现对于所有updateXXX方法重复以下内容:

updater方法不会更新基础数据库;而是调用updateRow或insertRow方法来更新数据库。

“好极了,我想。我可以做这样的事情:

while(rs.next()) { 
  Retrieve desired values by column name
  if(condition) {
    Invoke rs.updateXXX() on the desired column name with the new value
  }
  Business Logic
  ...
}

请记住,业务逻辑发生在while循环内

但是,令我沮丧的是,rs.updateXXX()似乎没有像我期望的那样生效。

幸运的是,我已经能够使用我从here:改编而成的一些示例代码来重新创建问题

首先,我们使用以下SQL指令创建示例数据库:

CREATE DATABASE EMP;
CREATE TABLE EMP.Employees
(
  id INT NOT NULL,
  age INT NOT NULL,
  first VARCHAR(255),
  last VARCHAR(255),
  PRIMARY KEY ( id )
);
INSERT INTO EMP.Employees VALUES (100, 18, 'Zara', 'Ali'), (101, 25, 'Mahnaz', 'Fatima'), (102, 30, 'Zaid', 'Khan'), (103, 28, 'Sumit', 'Mittal');

然后我们有以下JDBC代码:

// Adapted from https://www.tutorialspoint.com/jdbc

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCStudy {
    // JDBC driver name and database URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
    static final String DB_URL = "jdbc:mysql://localhost/EMP";

    //  Database credentials
    static final String USER = "username";
    static final String PASS = "password";

    public static void main(String[] args) {
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");

            System.out.println("Connecting to database...");
            conn = DriverManager.getConnection(DB_URL,USER,PASS);

            System.out.println("Creating statement...");

            testJDBC(conn);
        }
        catch(SQLException se){
            //Handle errors for JDBC
            se.printStackTrace();
        }
        catch(Exception e){
            //Handle errors for Class.forName
            e.printStackTrace();
        }
        finally {
            try{
                if(conn!=null)
                    conn.close();
            }
            catch(SQLException se){
                se.printStackTrace();
            }
        }
        System.out.println("Goodbye!");
    }


    private static void testJDBC(Connection conn) throws SQLException {
          System.out.println("Creating statement...");
          Statement stmt = conn.createStatement(
                               ResultSet.TYPE_SCROLL_INSENSITIVE,
                               ResultSet.CONCUR_UPDATABLE);
          String sql = "SELECT id, first, last, age FROM Employees";
          ResultSet rs = stmt.executeQuery(sql);

          //Loop through result set and add 5 in age
          //Move to BFR postion so while-loop works properly
          rs.beforeFirst();
          //Extract data from result set
          while(rs.next()){
             String firstName = rs.getString("first");
             int newAge = rs.getInt("age") + 5;
             rs.updateInt( "age", newAge );

             int retrievedAge = rs.getInt("age");
             System.out.println(firstName + "> " + "New age, Retrieved age: (" + newAge + ", " + retrievedAge + ")");
             // I was expecting the The newAge and retrievedAge to be the same
          }
          stmt.close();     
    }
}

我从该程序获得以下输出:

Zara> New age, Retrieved age: (23, 18)
Mahnaz> New age, Retrieved age: (30, 25)
Zaid> New age, Retrieved age: (35, 30)
Sumit> New age, Retrieved age: (33, 28)

我期望新年龄和已检索年龄具有相同的值。


问题]:为什么rs.updateInt( "age", newAge )没有生效?

java jdbc
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.