将许多行插入到H2数据库中,然后将其读取到列表中

时间:2018-10-27 18:22:47

标签: java prepared-statement h2

我想在H2表中插入一些行,然后再次将其写到列表中。

但是,我总是将resultSet放入最后执行的语句中。

此外,我总是会收到此错误:

  

org.h2.jdbc.JdbcSQLException:锁定“用户名” nicht gefunden   找不到“用户名”列[42122-197]

这是我的代码:

 @Test
 public void testInsertAndReadForList() throws SQLException {
        User userA = new User(null, "UserA", "passwordA");
        User userB = new User(null, "UserB", "passwordB"

        String insertStmt = "INSERT INTO user(username, password) " +
        "VALUES(?, ?)";

       PreparedStatement insertPrepStmt = connection.prepareStatement(insertStmt, Statement.RETURN_GENERATED_KEYS);
       insertPrepStmt.setString(1, userA.getUsername());
       insertPrepStmt.setString(2, userA.getPassword());
       insertPrepStmt.executeUpdate();

       insertPrepStmt.setString(1, userB.getUsername());
       insertPrepStmt.setString(2, userB.getPassword());
       insertPrepStmt.executeUpdate();

       int affectedRows = insertPrepStmt.executeUpdate();
       assertThat(affectedRows).isEqualTo(1);

       ResultSet resultSet = insertPrepStmt.getGeneratedKeys();

       List<User> newResultSet = new ArrayList<>();
       int i = 0;

       while(resultSet.next()) {
           i++;
           newResultSet.add(new User(resultSet.getLong(i), 
           resultSet.getString("username"), resultSet.getString("password")));
       }
   }

也许有人可以告诉我,我在这里做错了吗?

1 个答案:

答案 0 :(得分:0)

我能够自己解决:

int counter = 0;

PreparedStatement insertPrepStmt = connection.prepareStatement(insertStmt, Statement.RETURN_GENERATED_KEYS);
insertPrepStmt.setString(1, userA.getUsername());
insertPrepStmt.setString(2, userA.getPassword());
int affectedRows = insertPrepStmt.executeUpdate();
assertThat(affectedRows).isEqualTo(1).isGreaterThan(0);
ResultSet resultSet = insertPrepStmt.getGeneratedKeys();
assertThat(resultSet.next()).isTrue();
counter++;

insertPrepStmt.setString(1, userB.getUsername());
insertPrepStmt.setString(2, userB.getPassword());
affectedRows = insertPrepStmt.executeUpdate();
assertThat(affectedRows).isEqualTo(1).isGreaterThan(0);
resultSet = insertPrepStmt.getGeneratedKeys();
assertThat(resultSet.next()).isTrue();
counter++;

readFromDatabase(resultSet, counter); <!-- and here the reading will be done via counter variable -->