How to find column datatype from ResultSetMetaData in Java?
--Before executing java program execute these database scripts >
create table EMPLOYEE(ID number(4),
NAME varchar2(22),
CREATION_DATE date,
FILE_CLOB clob,
FILE_BLOB blob);
commit;
--If table already exists then execute the DROP command >
drop table EMPLOYEE;
Programs JDBC- How to find column datatype from ResultSetMetaData in Java?
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ResultSetMetaDataColumnDatatype {
public static void main(String... arg) {
Connection con = null;
PreparedStatement prepStmt = null;
ResultSet rs = null;
try {
// registering Oracle driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
// getting connection
con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:orcl",
"ankit", "Oracle123");
prepStmt = con.prepareStatement("select * from EMPLOYEE");
//Obtain ResultSet
rs = prepStmt.executeQuery();
//Obtain ResultSetMetaData
ResultSetMetaData rsmd = rs.getMetaData();
int totalNumberOfColumnsInTable = rsmd.getColumnCount();
System.out.println("\nTotal number of columns in table = "
+ totalNumberOfColumnsInTable);
for(int i=1; i<=totalNumberOfColumnsInTable; i++){
System.out.println("\n"+rsmd.getColumnTypeName(i));
if(rsmd.getColumnTypeName(i).equals("NUMBER")){
System.out.println("Column's datatype is NUMBER" );
}
else if(rsmd.getColumnTypeName(i).equals("VARCHAR2")){
System.out.println("Column's datatype is VARCHAR2" );
}
else if(rsmd.getColumnTypeName(i).equals("DATE")){
System.out.println("Column's datatype is DATE" );
}
else if(rsmd.getColumnTypeName(i).equals("CLOB")){
System.out.println("Column's datatype is CLOB" );
}
else if(rsmd.getColumnTypeName(i).equals("BLOB")){
System.out.println("Column's datatype is BLOB" );
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
finally{
try {
if(rs!=null) rs.close(); //close resultSet
if(prepStmt!=null) prepStmt.close(); //close PreparedStatement
if(con!=null) con.close(); // close connection
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
/*OUTPUT
Total number of columns in table = 5
NUMBER
Column's datatype is NUMBER
VARCHAR2
Column's datatype is VARCHAR2
DATE
Column's datatype is DATE
CLOB
Column's datatype is CLOB
BLOB
Column's datatype is BLOB
*/
|
Related >