Java program to get data type of column field

In this example java program we have to get the data
type of the database table fields. For this purpose we have established database
connection via JDBC and after connecting database we have get the data
tables meta data for getting the data type of the table columns. Here we have
used MySQL database for connection with the data table. Table structure for webpages table of database
"any" is as follows:

ResultSet rs = st.executeQuery("SELECT * FROM webpages");
ResultSetMetaData rsmd = rs.getMetaData();
Above line of code gets ResultSetMetaData object
which will be further used for getting related information. We can use the getColumnCount()
methods for getting the column index and these index will be used for
getting column type and with the getColumnTypeName(index) method of ResultSetMetaData
class.
Here is the example code of GetColumnDataType.java as
follows:
GetColumnDataType.java
import java.sql.*;
public class GetColumnDataType {
public static void main(String[] args) throws Exception {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String username = "root";
String password = "root";
String dbName= "any";
Class.forName(driver);
Connection conn = DriverManager.getConnection(
url+dbName,
username,
password);
System.out.println("Connected");
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM webpages");
ResultSetMetaData rsmd = rs.getMetaData();
int NumOfCol = rsmd.getColumnCount();
for(int i=1;i<=NumOfCol;i++)
{
System.out.println("Name of ["+i+"] Column data type is ="
+rsmd.getColumnTypeName(i));
}
st.close();
conn.close();
}
}
|
Output:
C:\javaexamples>javac GetColumnDataType.java
C:\javaexamples>java GetColumnDataType
Connected
Name of [1] Column data type is =DOUBLE
Name of [2] Column data type is =VARCHAR
Name of [3] Column data type is =VARCHAR
Name of [4] Column data type is =BLOB |
Download Source Code

|