Ali Bassam
Ali Bassam

Reputation: 9959

How to return Column number from Oracle to Java

I used the following query to get the number of columns.

select count(*) from all_tab_columns where owner='IULPROJECT' and table_name='SUPPLIERS';

This query worked in Oracle command line, I got the number 5, but how can I return this number in Java?

In Java:

stmt=conn.createStatement();
query="select count(*) from all_tab_columns where owner='IULPROJECT' and table_name='SUPPLIERS' ";
rset=stmt.executeQuery(query);
System.out.println(stmt); //<-- what should I put here to get back my number "5" ?

Upvotes: 0

Views: 505

Answers (5)

David Aldridge
David Aldridge

Reputation: 52346

Just as background info, note that

select count(*) from ...

will always return exactly one row that will be greater than or equal to zero and which will never be null (the latter being true for all:

count(*)

calls).

I put this as a comment initially but * = italics and I couldn't find a way of escaping it

Upvotes: 0

Samurai
Samurai

Reputation: 843

Use rset.getInt(1). It will return the valuse of the first column.

while(rset.next){ System.out.println(rset.getInt(1));}

Upvotes: 1

Simon Dorociak
Simon Dorociak

Reputation: 33505

Your data are already in ResultSet that contains one column so you must call first next() because ResultSet Cursor type is implicitly positioned to row before first. So call next() method and then with count = rset.getInt(1) you will get your data.

 rset=stmt.executeQuery(query);
    int count = 0;
    while (rset.next()) {

    count = rset.getInt(1); // numbering of columns starts from 1 not from 0

    }
    System.out.println(count);

Hope it helps you. Regards man

Upvotes: 3

Chandra Sekhar
Chandra Sekhar

Reputation: 19502

Your query will return a table with one row and one column as count(*) is a group function. So after getting the ResultSet, go to the first row using next() and then get the value using getInt()

stmt=conn.createStatement();
query="select count(*) from all_tab_columns where owner='IULPROJECT' and table_name='SUPPLIERS' ";
rset=stmt.executeQuery(query);
rset.next();
System.out.println(rset.getInt(1)); 

Upvotes: 1

Fahim Parkar
Fahim Parkar

Reputation: 31637

rset=stmt.executeQuery(query);
while (rset.next()) {
    System.out.println(rset.getInt(1));
}

Upvotes: 1

Related Questions