| Author |
how can i get column name of a table
|
zb cong
Ranch Hand
Joined: Jan 14, 2002
Posts: 403
|
|
hello in one of my project,i want to get the column names of a unknown table,i can get it by the ResultSetMetaData.getColumnCount(int col) method,but i must execute a query first,because i know nothing about the table,the only choice is "select * from myTable",then navigate the resultset.but maybe this table have thousands of records,i only want to get the COLUMN NAME,not the record,so this method is not effective,who can give me a more effective code snippet?such as retrieve the column names of the emp table(in oracle sample database-----scott/tiger). thank you!
|
 |
Calvin Yan
Greenhorn
Joined: Jun 25, 2003
Posts: 19
|
|
you may concentrate on the part of ResultSetMetaData instance: public class odbctest { public static void main(String[] argu) { try { Connection conn; Statement st; ResultSet rs; ResultSetMetaData rsmd; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance(); conn = DriverManager.getConnection("jdbc dbc:book"); st = conn.createStatement(); rs = st.executeQuery("select * from [Sheet1$]"); rsmd = rs.getMetaData(); int count = rsmd.getColumnCount(); System.out.println(count); String[] field = new String[count]; if(count != 0) { for(int i=0; i<count; i++) { field[i] = rsmd.getColumnName(i+1); //System.out.println(s); } } rs = st.executeQuery("select * from [Sheet1$]"); while(rs.next()) { String s = rs.getString(1); System.out.println(s); } } catch(Exception e) { System.out.println(e.toString()); } } }
|
I will do the best with what God gave me!
|
 |
Avi Abrami
Ranch Hand
Joined: Oct 11, 2000
Posts: 1112
|
|
Hi Zhebin, Have you seen the answers that I (and Elango) have provided to this very same question that you posted at the Oracle (OTN) forums? Good Luck, Avi.
|
 |
zb cong
Ranch Hand
Joined: Jan 14, 2002
Posts: 403
|
|
to Calvin: i don't want to execute such operation: rs = st.executeQuery("select * from [Sheet1$]"); because i only want to get the column name,not any record in the table,such a operation maybe more resource-consuming,there may be millions of record in the table. to Avi: could you give me the CONCRETE link to the post,the link you have provided is pointed to the main page of the otn forum.
|
 |
zb cong
Ranch Hand
Joined: Jan 14, 2002
Posts: 403
|
|
hi Avi i have got it,that is just me,it is funny.
|
 |
Wayne L Johnson
Ranch Hand
Joined: Sep 03, 2003
Posts: 399
|
|
One possible way to "cheat"--and I've tested this against several different databases--is to force the query to return no rows, something like: rs = st.executeQuery("select * from [Sheet1$] where 1 = 2"); I've tested this against tables with over one million records and it returned almost immediately. But I still got the ResultSetMetaData and was able to determine the column names and types.
|
 |
 |
|
|
subject: how can i get column name of a table
|
|
|