01 /**
02 * What if we don't know the schema of a ResultSet?
03 * ResultSetMetaData rsmd = rs.getMetaData();
04 rsmd.getColumnCount();
05 rsmd.getColumnName(index);
06 rsmd.getColumnTypeName(index);// return column type used by java.sql.Types
07 rsmd.getColumnType(index); // return column type used by the database
08 */
09
10 package com.company.tests;
11 import java.sql.*;
12 import com.company.utils.*;
13
14 public class Test0033 {
15
16 public static void main(String[] args){
17 try{
18 Connection conn = JDBCUtil.getConnection();
19
20 Statement st= conn.createStatement();
21 String sql = "select * from Sample";
22 ResultSet rs = st.executeQuery(sql);
23
24 ResultSetMetaData rsmd = rs.getMetaData();
25 int n = rsmd.getColumnCount();
26 String[] colomns = new String[n+1];
27 String[] types = new String[n+1];
28 for(int i = 1 ; i <=n;i++){
29 colomns[i] = rsmd.getColumnName(i);
30 types[i] = rsmd.getColumnTypeName(i);
31
32 System.out.print(colomns[i] + "(" +types[i]+ ")");
33 }
34 System.out.println("");
35 while(rs.next()){
36 for(int i = 1 ; i <=n;i++){
37 System.out.print(rs.getObject(i).toString() + " ");
38 }
39 System.out.println("");
40 }
41 rs.close();
42 }catch(Exception e){
43 e.printStackTrace();
44 }
45 }
46 }
02 * What if we don't know the schema of a ResultSet?
03 * ResultSetMetaData rsmd = rs.getMetaData();
04 rsmd.getColumnCount();
05 rsmd.getColumnName(index);
06 rsmd.getColumnTypeName(index);// return column type used by java.sql.Types
07 rsmd.getColumnType(index); // return column type used by the database
08 */
09
10 package com.company.tests;
11 import java.sql.*;
12 import com.company.utils.*;
13
14 public class Test0033 {
15
16 public static void main(String[] args){
17 try{
18 Connection conn = JDBCUtil.getConnection();
19
20 Statement st= conn.createStatement();
21 String sql = "select * from Sample";
22 ResultSet rs = st.executeQuery(sql);
23
24 ResultSetMetaData rsmd = rs.getMetaData();
25 int n = rsmd.getColumnCount();
26 String[] colomns = new String[n+1];
27 String[] types = new String[n+1];
28 for(int i = 1 ; i <=n;i++){
29 colomns[i] = rsmd.getColumnName(i);
30 types[i] = rsmd.getColumnTypeName(i);
31
32 System.out.print(colomns[i] + "(" +types[i]+ ")");
33 }
34 System.out.println("");
35 while(rs.next()){
36 for(int i = 1 ; i <=n;i++){
37 System.out.print(rs.getObject(i).toString() + " ");
38 }
39 System.out.println("");
40 }
41 rs.close();
42 }catch(Exception e){
43 e.printStackTrace();
44 }
45 }
46 }
There are also other useful functions in ResultSetMetaData. Go check the API!
PS: JDBCUtil.getConnection() please refer to my last post:
http://bosbluebluesky.blogspot.com/2012/04/jdbc-configuration-and-implementation.html
PS: JDBCUtil.getConnection() please refer to my last post:
http://bosbluebluesky.blogspot.com/2012/04/jdbc-configuration-and-implementation.html
No comments:
Post a Comment