Java SQL Type getColumnType(Connection conn, String table, String column)

Here you can find the source of getColumnType(Connection conn, String table, String column)

Description

Returns the type (as specified in java.sql.Types for the specified column in the specified table.

License

Open Source License

Declaration

public static int getColumnType(Connection conn, String table, String column) throws SQLException 

Method Source Code

//package com.java2s;

import java.sql.Connection;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Main {
    /**/*from  w  ww  .j av a 2 s.c o  m*/
     * Returns the type (as specified in {@link java.sql.Types} for the specified column in the
     * specified table.
     */
    public static int getColumnType(Connection conn, String table, String column) throws SQLException {
        ResultSet rs = getColumnMetaData(conn, table, column);
        try {
            return rs.getInt("DATA_TYPE");
        } finally {
            rs.close();
        }
    }

    /**
     * Helper function for {@link #getColumnType}, etc.
     */
    protected static ResultSet getColumnMetaData(Connection conn, String table, String column) throws SQLException {
        ResultSet rs = conn.getMetaData().getColumns("", "", table, column);
        while (rs.next()) {
            String tname = rs.getString("TABLE_NAME");
            String cname = rs.getString("COLUMN_NAME");
            if (tname.equals(table) && cname.equals(column)) {
                return rs;
            }
        }
        throw new SQLException("Table or Column not defined. [table=" + table + ", col=" + column + "].");
    }

    /**
     * Closes the supplied JDBC statement and gracefully handles being passed null (by doing
     * nothing).
     */
    public static void close(Statement stmt) throws SQLException {
        if (stmt != null) {
            stmt.close();
        }
    }

    /**
     * Closes the supplied JDBC connection and gracefully handles being passed null (by doing
     * nothing).
     */
    public static void close(Connection conn) throws SQLException {
        if (conn != null) {
            conn.close();
        }
    }
}

Related

  1. getClass(int sqlType, int precision, int scale)
  2. getClassByJdbcType(int type, int decimalDigits)
  3. getCloverTypeFromJdbcType(int jdbcDataType)
  4. getColumeTypeDesc(Class clazz)
  5. getColumnClass(int sqlType)
  6. getColumnType(String type)
  7. getConnection(String jdbcUrl, Properties properties)
  8. getDbDataType(Object o)
  9. getDefaultPrecision(int sqlType)