Connection获取数据库、表、字段元数据

前言

使用JDBC Connection 获取数据库信息,表信息和字段信息元数据。


提示:这里我使用 JDBC连接 ES 作为样例,其他数据源一样

一、获取数据库元数据

数据库元数据使用 connection.getMetaData().getCatalogs();

查看源码如下,可看到字段为 TABLE_CAT

    /**
     * Retrieves the catalog names available in this database.  The results
     * are ordered by catalog name.
     *
     * <P>The catalog column is:
     *  <OL>
     *  <LI><B>TABLE_CAT</B> String {@code =>} catalog name
     *  </OL>
     *
     * @return a <code>ResultSet</code> object in which each row has a
     *         single <code>String</code> column that is a catalog name
     * @exception SQLException if a database access error occurs
     */
    ResultSet getCatalogs() throws SQLException;

使用Connection 获取,代码如下,这里打印出所有数据库信息

    /**
     * 查看所有数据库.
     *
     * @param connection
     * @throws Exception
     */
    public static void showDatabases(Connection connection) throws Exception{
        ResultSet schemas = connection.getMetaData().getCatalogs();
        while (schemas.next()){
            System.out.println(schemas.getObject("TABLE_CAT"));
        }
    }

二、获取数据表元数据

查看表的元数据,是为了查询数据库里所有的表信息,如表名、表描述等等

方法是 connection.getMetaData().getTables,查看源码如下:

/**
     * Retrieves a description of the tables available in the given catalog.
     * Only table descriptions matching the catalog, schema, table
     * name and type criteria are returned.  They are ordered by
     * <code>TABLE_TYPE</code>, <code>TABLE_CAT</code>,
     * <code>TABLE_SCHEM</code> and <code>TABLE_NAME</code>.
     * <P>
     * Each table description has the following columns:
     *  <OL>
     *  <LI><B>TABLE_CAT</B> String {@code =>} table catalog (may be <code>null</code>)
     *  <LI><B>TABLE_SCHEM</B> String {@code =>} table schema (may be <code>null</code>)
     *  <LI><B>TABLE_NAME</B> String {@code =>} table name
     *  <LI><B>TABLE_TYPE</B> String {@code =>} table type.  Typical types are "TABLE",
     *                  "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY",
     *                  "LOCAL TEMPORARY", "ALIAS", "SYNONYM".
     *  <LI><B>REMARKS</B> String {@code =>} explanatory comment on the table
     *  <LI><B>TYPE_CAT</B> String {@code =>} the types catalog (may be <code>null</code>)
     *  <LI><B>TYPE_SCHEM</B> String {@code =>} the types schema (may be <code>null</code>)
     *  <LI><B>TYPE_NAME</B> String {@code =>} type name (may be <code>null</code>)
     *  <LI><B>SELF_REFERENCING_COL_NAME</B> String {@code =>} name of the designated
     *                  "identifier" column of a typed table (may be <code>null</code>)
     *  <LI><B>REF_GENERATION</B> String {@code =>} specifies how values in
     *                  SELF_REFERENCING_COL_NAME are created. Values are
     *                  "SYSTEM", "USER", "DERIVED". (may be <code>null</code>)
     *  </OL>
     *
     * <P><B>Note:</B> Some databases may not return information for
     * all tables.
     *
     * @param catalog a catalog name; must match the catalog name as it
     *        is stored in the database; "" retrieves those without a catalog;
     *        <code>null</code> means that the catalog name should not be used to narrow
     *        the search
     * @param schemaPattern a schema name pattern; must match the schema name
     *        as it is stored in the database; "" retrieves those without a schema;
     *        <code>null</code> means that the schema name should not be used to narrow
     *        the search
     * @param tableNamePattern a table name pattern; must match the
     *        table name as it is stored in the database
     * @param types a list of table types, which must be from the list of table types
     *         returned from {@link #getTableTypes},to include; <code>null</code> returns
     * all types
     * @return <code>ResultSet</code> - each row is a table description
     * @exception SQLException if a database access error occurs
     * @see #getSearchStringEscape
     */
    ResultSet getTables(String catalog, String schemaPattern,
                        String tableNamePattern, String types[]) throws SQLException;

如上可知,每个表格描述包含以下列:

  • TABLE_CAT 字符串=>表目录(可能为null )
  • TABLE_SCHEM 字符串=>表格式(可能为null )
  • TABLE_NAME 字符串=>表名
  • TABLE_TYPE 字符串=>表类型。 典型的类型是“TABLE”,“VIEW”,“SYSTEM TABLE”,“GLOBAL TEMPORARY”,“LOCAL TEMPORARY”,“ALIAS”,“SYNONYM”。
  • REMARKS 字符串 =>对表的解释性评论
  • TYPE_CAT 字符串=>类型目录(可能为null )
  • TYPE_SCHEM 字符串=>类型模式(可能是null )
  • TYPE_NAME 字符串=>类型名称(可能为null )
  • SELF_REFERENCING_COL_NAME 字符串=>类型表的指定“标识符”列的名称(可能为null )
  • REF_GENERATION String =>指定如何创建SELF_REFERENCING_COL_NAME中的值。 值为“SYSTEM”,“USER”,“DERIVED”。 (可能是null )

获取代码如下,查看数据库所有表信息

    /**
     * 查看数据库所有表.
     *
     * @param connection
     * @throws Exception
     */
    public static void showTables(Connection connection) throws Exception{
        ResultSet tables = connection.getMetaData().getTables(null, null, null, null);
        while (tables.next()) {
//            System.out.println(tables.getString("TABLE_NAME"));
            String TABLE_CAT = tables.getString("TABLE_CAT");
            String TABLE_SCHEM = tables.getString("TABLE_SCHEM");
            String TABLE_NAME = tables.getString("TABLE_NAME");
            String TABLE_TYPE = tables.getString("TABLE_TYPE");
            String REMARKS = tables.getString("REMARKS");
            log.info("表类别:{}、表模式:{}、表名称:{}、表类型:{}、表描述:{}", TABLE_CAT, TABLE_SCHEM, TABLE_NAME, TABLE_TYPE, REMARKS);
        }
    }

三、获取数据表字段元数据

获取数据库表字段元数据可以使用 connection.getMetaData().getColumns方法

每列描述具有以下列:

  • TABLE_CAT字符串=>表目录(可能为null )
  • TABLE_SCHEM字符串=>表格式(可能是null )
  • TABLE_NAME String =>表名
  • COLUMN_NAME字符串=>列名
  • DATA_TYPE int => SQL类型
  • TYPE_NAME String =>数据源相关类型名称,对于UDT,类型名称是完全限定的
  • COLUMN_SIZE int =>列大小。
  • 不使用BUFFER_LENGTH 。
  • DECIMAL_DIGITS int =>小数位数。 对于DECIMAL_DIGITS不适用的数据类型,返回空值。
  • NUM_PREC_RADIX int =>基数(通常为10或2)
  • NULLABLE int =>允许NULL。
    columnNoNulls - 可能不允许NULL值
    columnNullable - 绝对允许NULL值
    columnNullableUnknown - 可空性未知
  • REMARKS 字符串=>注释描述列(可能为null )
  • COLUMN_DEF字符串=>列的默认值,当值以单引号括起时,应将其解释为字符串(可能为null )
  • 未使用SQL_DATA_TYPE int =>
  • SQL_DATETIME_SUB int =>未使用
  • CHAR_OCTET_LENGTH int =>用于char类型列中最大字节数
  • ORDINAL_POSITION int =>表中的列索引(从1开始)
  • IS_NULLABLE字符串=> ISO规则用于确定列的可空性。
    YES —如果列可以包含NULL
    否—如果列不能包含NULL
    空字符串—如果列的可空性是未知的
  • SCOPE_CATALOG字符串=>目录表的,它是引用属性的范围( null如果DATA_TYPE不是REF)
  • SCOPE_SCHEMA字符串=>作为参考属性范围的表格( null如果DATA_TYPE不是REF)
  • SCOPE_TABLE字符串=>表名称,该引用属性的(范围null如果DATA_TYPE不是REF)
  • SOURCE_DATA_TYPE短=>源类型来自java.sql.Types的独特的类型或用户生成Ref类型,SQL型的( null如果DATA_TYPE不是DISTINCT或用户生成的REF)
  • IS_AUTOINCREMENT字符串=>指示此列是否自动递增
    YES —如果列自动递增
    否—如果列不自动递增
    空字符串—如果无法确定列是否自动递增
  • IS_GENERATEDCOLUMN字符串=>指示这是否是生成的列
    是—如果这是一个生成的列
    否—如果这不是一个生成的列
    空字符串—如果无法确定这是否是生成的列

COLUMN_SIZE列指定给定列的列大小。 对于数值数据,这是最大精度。 对于字符数据,这是字符长度。 对于datetime数据类型,这是String表示形式的长度(假定分数秒分量的最大允许精度)。 对于二进制数据,这是以字节为单位的长度。 对于ROWID数据类型,这是以字节为单位的长度。 对于列大小不适用的数据类型,返回空值。

使用代码获取所有字段,例如:这里查询 ‘test_index’ 表的所有字段

    /**
     * 查看表所有字段.
     *
     * @param connection
     * @throws Exception
     */
    public static void showColumns(Connection connection) throws Exception{
        ResultSet tables = connection.getMetaData().getColumns(null, null, "test_index", null);
        while (tables.next()) {
            String TABLE_CAT = tables.getString("TABLE_CAT");
            String TABLE_SCHEM = tables.getString("TABLE_SCHEM");
            String TABLE_NAME = tables.getString("TABLE_NAME");
            String columnName = tables.getString("COLUMN_NAME");
            String typeName = tables.getString("TYPE_NAME");
            String columnSize = tables.getString("COLUMN_SIZE");
            String REMARKS = tables.getString("REMARKS");
            log.info("表类别:{}、表模式:{}、表名称:{}、字段名称:{}、字段类型:{}、字段大小:{}、字段描述:{}",
                    TABLE_CAT, TABLE_SCHEM, TABLE_NAME, columnName, typeName, columnSize, REMARKS);
        }
    }

输出如下

表类别:my-application、表模式:null、表名称:test_index、字段名称:hh、字段类型:TEXT、字段大小:2147483647、字段描述:null
表类别:my-application、表模式:null、表名称:test_index、字段名称:hh.keyword、字段类型:KEYWORD、字段大小:32766、字段描述:null
表类别:my-application、表模式:null、表名称:test_index、字段名称:msg、字段类型:TEXT、字段大小:2147483647、字段描述:null
表类别:my-application、表模式:null、表名称:test_index、字段名称:msg.keyword、字段类型:KEYWORD、字段大小:32766、字段描述:null
表类别:my-application、表模式:null、表名称:test_index、字段名称:msg2、字段类型:TEXT、字段大小:2147483647、字段描述:null
表类别:my-application、表模式:null、表名称:test_index、字段名称:msg2.keyword、字段类型:KEYWORD、字段大小:32766、字段描述:null

总结

本文样例的完整代码见下篇文章《实现JDBC连接ES查询

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
private static void printTableMetaInfo(Session session) { Connection connection = session.connection(); try { DatabaseMetaData metaData = connection.getMetaData(); ResultSet result = metaData.getColumns(null, null, NameOfTable, null); String strInJava = ""; String typeInJava; while (result.next()) { String columnName = result.getString(4); if ("stampTime".equalsIgnoreCase(columnName)) { continue; } int columnType = result.getInt(5); String nameFirstLetterLower = columnName.substring(0, 1).toLowerCase() + columnName.substring(1); switch (columnType) { case Types.VARCHAR: case Types.LONGVARCHAR: case Types.LONGNVARCHAR: case Types.NVARCHAR: case Types.CHAR: typeInJava = "String"; break; case Types.TINYINT: case Types.SMALLINT: case Types.INTEGER: typeInJava = useInteger ? "Integer" : "int"; break; case Types.TIMESTAMP: case Types.BINARY: typeInJava = "Calendar"; break; case Types.DECIMAL: typeInJava = "BigDecimal"; break; case Types.BIGINT: typeInJava = "BigInteger"; break; case Types.LONGVARBINARY: typeInJava = "byte[]"; break; case Types.DATE: typeInJava = "Calendar"; break; default: throw new Exception("Unknown type " + columnType + " and column is " + columnName); } strInJava += " private " + typeInJava + " " + nameFirstLetterLower + ";\n"; // strInHibernate += "\n"; } String str = "import javax.persistence.Entity;\n" + "import javax.persistence.Id;\n" + "import javax.persistence.Table;\n" + "import java.util.Calendar;\n\n"; str += "@Entity\n"; str += "@Table(name=\"$\")\n".replace("$", NameOfTable); str += "public class $ {\n".replace("$", NameOfTable.substring(2)); str += "\n @Id\n"; str += strInJava; str += "}"; System.out.println(str); StringSelection stringSelection = new StringSelection(str); Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard(); clpbrd.setContents(stringSelection, null); } catch (Exception e) { e.printStackTrace(); }
package com.hexiang.utils; import java.sql.*; import java.util.*; /** * * Title: 数据库工具类 * * * Description: 将大部分的数据库操作放入这个类中, 包括数据库连接的建立, 自动释放等. * * * @author beansoft 日期: 2004年04月 * @version 2.0 */ public class DatabaseUtil { /** 数据库连接 */ private java.sql.Connection connection; /** * All database resources created by this class, should be free after all * operations, holds: ResultSet, Statement, PreparedStatement, etc. */ private ArrayList resourcesList = new ArrayList(5); public DatabaseUtil() { } /** 关闭数据库连接并释放所有数据库资源 */ public void close() { closeAllResources(); close(getConnection()); } /** * Close given connection. * * @param connection * Connection */ public static void close(Connection connection) { try { connection.close(); } catch (Exception ex) { System.err.println("Exception when close a connection: " + ex.getMessage()); } } /** * Close all resources created by this class. */ public void closeAllResources() { for (int i = 0; i < this.getResourcesList().size(); i++) { closeJDBCResource(getResourcesList().get(i)); } } /** * Close a jdbc resource, such as ResultSet, Statement, Connection.... All * these objects must have a method signature is void close(). * * @param resource - * jdbc resouce to close */ public void closeJDBCResource(Object resource) { try { Class clazz = resource.getClass(); java.lang.reflect.Method method = clazz.getMethod("close", null); method.invoke(resource, null); } catch (Exception e) { // e.printStackTrace(); } } /** * 执行 SELECT 等 SQL 语句并返回结果集. * * @param sql * 需要发送到数据库 SQL 语句 * @return a ResultSet object that contains the data produced * by the given query; never null */ public ResultSet executeQuery(String sql) { try { Statement statement = getStatement(); ResultSet rs = statement.executeQuery(sql); this.getResourcesList().add(rs); this.getResourcesList().add(statement);// BUG fix at 2006-04-29 by BeanSoft, added this to res list // MySql 数据库要求必需关闭 statement 对象, 否则释放不掉资源 // - 此观点错误, 因为关闭此对象后有时数据无法读出 //statement.close(); return rs; } catch (Exception ex) { System.out.println("Error in executeQuery(\"" + sql + "\"):" + ex); // ex.printStackTrace(); return null; } } /** * Executes the given SQL statement, which may be an INSERT, * UPDATE, or DELETE statement or an SQL * statement that returns nothing, such as an SQL DDL statement. 执行给定的 SQL * 语句, 这些语句可能是 INSERT, UPDATE 或者 DELETE 语句, 或者是一个不返回任何东西的 SQL 语句, 例如一个 SQL * DDL 语句. * * @param sql * an SQL INSERT,UPDATE or * DELETE statement or an SQL statement that * returns nothing * @return either the row count for INSERT, * UPDATE or DELETE statements, or * 0 for SQL statements that return nothing */ public int executeUpdate(String sql) { try { Statement statement = getStatement(); return statement.executeUpdate(sql); // MySql 数据库要求必需关闭 statement 对象, 否则释放不掉资源 // - 此观点错误, 因为关闭此对象后有时数据无法读出 //statement.close(); } catch (Exception ex) { System.out.println("Error in executeUpdate(): " + sql + " " + ex); //System.out.println("executeUpdate:" + sql); ex.printStackTrace(); } return -1; } /** * 返回记录总数, 使用方法: getAllCount("SELECT count(ID) from tableName") 2004-06-09 * 可滚动的 Statement 不能执行 SELECT MAX(ID) 之类的查询语句(SQLServer 2000) * * @param sql * 需要执行的 SQL * @return 记录总数 */ public int getAllCount(String sql) { try { Statement statement = getConnection().createStatement(); this.getResourcesList().add(statement); ResultSet rs = statement.executeQuery(sql); rs.next(); int cnt = rs.getInt(1); rs.close(); try { statement.close(); this.getResourcesList().remove(statement); } catch (Exception ex) { ex.printStackTrace(); } return cnt; } catch (Exception ex) { System.out.println("Exception in DatabaseUtil.getAllCount(" + sql + "):" + ex); ex.printStackTrace(); return 0; } } /** * 返回当前数据库连接. */ public java.sql.Connection getConnection() { return connection; } /** * 连接新的数据库对象到这个工具类, 首先尝试关闭老连接. */ public void setConnection(java.sql.Connection connection) { if (this.connection != null) { try { getConnection().close(); } catch (Exception ex) { } } this.connection = connection; } /** * Create a common statement from the database connection and return it. * * @return Statement */ public Statement getStatement() { // 首先尝试获取可滚动的 Statement, 然后才是普通 Statement Statement updatableStmt = getUpdatableStatement(); if (updatableStmt != null) return updatableStmt; try { Statement statement = getConnection().createStatement(); this.getResourcesList().add(statement); return statement; } catch (Exception ex) { System.out.println("Error in getStatement(): " + ex); } return null; } /** * Create a updatable and scrollable statement from the database connection * and return it. * * @return Statement */ public Statement getUpdatableStatement() { try { Statement statement = getConnection() .createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); this.getResourcesList().add(statement); return statement; } catch (Exception ex) { System.out.println("Error in getUpdatableStatement(): " + ex); } return null; } /** * Create a prepared statement and return it. * * @param sql * String SQL to prepare * @throws SQLException * any database exception * @return PreparedStatement the prepared statement */ public PreparedStatement getPreparedStatement(String sql) throws SQLException { try { PreparedStatement preparedStatement = getConnection() .prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); this.getResourcesList().add(preparedStatement); return preparedStatement; } catch (Exception ex) { ex.printStackTrace(); } return null; } /** * Return the resources list of this class. * * @return ArrayList the resources list */ public ArrayList getResourcesList() { return resourcesList; } /** * Fetch a string from the result set, and avoid return a null string. * * @param rs * the ResultSet * @param columnName * the column name * @return the fetched string */ public static String getString(ResultSet rs, String columnName) { try { String result = rs.getString(columnName); if (result == null) { result = ""; } return result; } catch (Exception ex) { } return ""; } /** * Get all the column labels * * @param resultSet * ResultSet * @return String[] */ public static String[] getColumns(ResultSet resultSet) { if (resultSet == null) { return null; } try { ResultSetMetaData metaData = resultSet.getMetaData(); int numberOfColumns = metaData.getColumnCount(); if (numberOfColumns <= 0) { return null; } String[] columns = new String[numberOfColumns]; //System.err.println("numberOfColumns=" + numberOfColumns); // Get the column names for (int column = 0; column < numberOfColumns; column++) { // System.out.print(metaData.getColumnLabel(column + 1) + "\t"); columns[column] = metaData.getColumnName(column + 1); } return columns; } catch (Exception ex) { ex.printStackTrace(); } return null; } /** * Get the row count of the result set. * * @param resultset * ResultSet * @throws SQLException * if a database access error occurs or the result set type is * TYPE_FORWARD_ONLY * @return int the row count * @since 1.2 */ public static int getRowCount(ResultSet resultset) throws SQLException { int row = 0; try { int currentRow = resultset.getRow(); // Remember old row position resultset.last(); row = resultset.getRow(); if (currentRow > 0) { resultset.absolute(row); } } catch (Exception ex) { ex.printStackTrace(); } return row; } /** * Get the column count of the result set. * * @param resultSet * ResultSet * @return int the column count */ public static int getColumnCount(ResultSet resultSet) { if (resultSet == null) { return 0; } try { ResultSetMetaData metaData = resultSet.getMetaData(); int numberOfColumns = metaData.getColumnCount(); return numberOfColumns; } catch (Exception ex) { ex.printStackTrace(); } return 0; } /** * Read one row's data from result set automatically and put the result it a * hashtable. Stored as "columnName" = "value", where value is converted to * String. * * @param resultSet * ResultSet * @return Hashtable */ public static final Hashtable readResultToHashtable(ResultSet resultSet) { if (resultSet == null) { return null; } Hashtable resultHash = new Hashtable(); try { String[] columns = getColumns(resultSet); if (columns != null) { // Read data column by column for (int i = 0; i < columns.length; i++) { resultHash.put(columns[i], getString(resultSet, columns[i])); } } } catch (Exception ex) { ex.printStackTrace(); } return resultHash; } /** * Read data from result set automatically and put the result it a * hashtable. Stored as "columnName" = "value", where value is converted to * String. * * Note: assume the default database string encoding is ISO8859-1. * * @param resultSet * ResultSet * @return Hashtable */ @SuppressWarnings("unchecked") public static final Hashtable readResultToHashtableISO(ResultSet resultSet) { if (resultSet == null) { return null; } Hashtable resultHash = new Hashtable(); try { String[] columns = getColumns(resultSet); if (columns != null) { // Read data column by column for (int i = 0; i < columns.length; i++) { String isoString = getString(resultSet, columns[i]); try { resultHash.put(columns[i], new String(isoString .getBytes("ISO8859-1"), "GBK")); } catch (Exception ex) { resultHash.put(columns[i], isoString); } } } } catch (Exception ex) { ex.printStackTrace(); } return resultHash; } /** Test this class. */ public static void main(String[] args) throws Exception { DatabaseUtil util = new DatabaseUtil(); // TODO: 从连接池工厂获取连接 // util.setConnection(ConnectionFactory.getConnection()); ResultSet rs = util.executeQuery("SELECT * FROM e_hyx_trans_info"); while (rs.next()) { Hashtable hash = readResultToHashtableISO(rs); Enumeration keys = hash.keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); System.out.println(key + "=" + hash.get(key)); } } rs.close(); util.close(); } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林志鹏JAVA

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值