Share on Google+Share on Google+

JDBC: Get Column Details Example

Advertisement
In this tutorial, we are describing how to get column details of a table using JDBC API.

JDBC: Get Column Details Example

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-

  • Field : It represents the column name.
  • Type : It shows you data type of column.
  • Collation : It represents the collation for non-binary string columns, and shows NULL for other columns. It is active when you use the FULL keyword.
  • Null : This field has Boolean value and shows YES if the field can store Null value otherwise shows NO.
  • Key : This field indicates the column index.

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)

Advertisements

Advertisement

Posted on: September 27, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.