Search code examples
javawhile-loopresultsetdbeaver

ResultSet in while loop cannot find column name


I am trying to print out a list of data from my user table in DBeaver, but whenever I run the Java program to return a list, I get an error saying "userid" column name not found. Do I need to change something in my while loop? Here is my code:

@Override
public List<User> findAll() {
    try(Connection conn = ConnectionUtil.getConnection()) {
    
        String sql = "SELECT * FROM user;";
        
        Statement statement = conn.createStatement();
        
        ResultSet result = statement.executeQuery(sql);
        
        List<User> list = new ArrayList<>();
        
        while (result.next()) {
            User user = new User();
            user.setUserId(result.getInt("userid"));
            user.setUsername(result.getString("username"));
            user.setPassword(result.getString("password"));
            user.setFirstName(result.getString("firstname"));
            user.setLastName(result.getString("lastname"));
            user.setEmail(result.getString("email"));
            
            list.add(user);
        }
        
        return list;

Here is my DBeaver table


Solution

  • user is a special keyword in PostgreSQL. That query is returning the username of the user logged in to the database. That's why columns don't match.

    You need to escape the table name for the query to work as expected:

    String sql = "SELECT * FROM \"user\";";