In this tutorial, we are describing how to get column details of a table using JDBC API.
Get Column details :
For displaying details of table columns, You can use "SHOW COLUMNS table_name" query in MySql. It shows information about the all the columns of specified table. You can also put conditions to get column details by using LIKE/WHERE Clause.
SHOW COLUMNS provides the following values for your every table column-
Example :
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
class GetColumnType {
public static void main(String[] args) {
System.out.println("Get column name and type of a table in JDBC...");
Connection con = null;
ResultSet rs = null;
Statement statement = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "students";
String driverName = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try {
Class.forName(driverName);
// Connecting to the database
con = DriverManager.getConnection(url + dbName, userName, password);
try {
statement = con.createStatement();
// Fetching Column details
String sql = "SHOW COLUMNS FROM student";
rs = statement.executeQuery(sql);
System.out.println("Column Name\tColumn Type");
System.out.println("---------------------------");
while (rs.next()) {
String name = rs.getString(1);
String type = rs.getString(2);
System.out.println(name + "\t\t" + type);
}
} catch (SQLException e) {
System.out.println(e);
}
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output :
Get column name and type of a table in JDBC... Column Name Column Type --------------------------- roll_no int(11) name varchar(30) course varchar(30)
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.