2

Postgres plpgsql function :

CREATE OR REPLACE FUNCTION usersList()
RETURNS TABLE(at varchar,name varchar,surname varchar)  AS $$
    BEGIN
        RETURN QUERY SELECT * FROM users;
    END;
$$ LANGUAGE plpgsql;

And java code

result = Pstatement.executeQuery("Select usersList() ");
while(result.next()) {
    System.out.println(result.getString(("at")));
    System.out.println(result.getString(("name")));
    System.out.println(result.getString(("surname")));
}

Java error sql exception message :

Message: The column name at was not found in this ResultSet.
SQLState: 42703
ErrorCode: 0

How can i return all table columns from a function and then print them in java ?

3
  • 2
    Try SELECT * FROM usersList(). Commented Apr 10, 2015 at 12:29
  • Yep, SELECT usersList() treats usersList() as a field, and packs the output columns into a single value (of type record). SELECT * FROM usersList() treats usersList() as a table, and gives you the result you're expecting. Commented Apr 10, 2015 at 12:40
  • Its really works.Thnx you. Added as answer to vote it as the right one !!! Commented Apr 10, 2015 at 12:42

2 Answers 2

1

Postgres plpgsql function :

CREATE OR REPLACE FUNCTION usersList()
RETURNS TABLE(at varchar,name varchar,surname varchar)  AS $$
    BEGIN
        RETURN QUERY SELECT * FROM users;
    END;
$$ LANGUAGE plpgsql;

And java code

result = Pstatement.executeQuery("SELECT * FROM usersList() ");
while(result.next()) {
    System.out.println(result.getString(("at")));
    System.out.println(result.getString(("name")));
    System.out.println(result.getString(("surname")));
}

Credits to RealSkeptic && Nick Barnes !!!

Sign up to request clarification or add additional context in comments.

Comments

0

You can use result.getMetaData().getColumnCount() to see how many columns you retrieved and then you can call result.getMetaData().getColumnName(x) to check the name of the column (replace x with the number of column).

So technically you should be able to write your code block like so:

result = Pstatement.executeQuery("Select usersList() ");
String mesites[];
while(result.next()) {
    int columnCount = result.getMetaData().getColumnCount();
    System.out.println("Found:"+columnCount+" columns.");
    for(int i=1; i<=columnCount; i++){
        System.out.println(result.getString(result.getMetaData().getColumnName(i)));
    }
}

Which should then print out any columns retrieved in that result set regardless of names (if any).

1 Comment

Found:1 columns. (" at1",name1,surname1) Found:1 columns. (" 123456",george,gtest) . . .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.