Java 通过JDBC查询数据库表结构(字段名称,类型,长度等)

我们如何知道,我们访问的数据库的表,有哪些字段,字段的类型是什么,长度限制是什么?

在实际工作中,我就遇到过,要做动态sql,比如insert,如果是数字就不要加引号,如果是字符就要加引号,还比如做基于数据库表的代码生成器等。我们都可能需要查表的表结构。

下面我就介绍一种通过JAVA最原始的JDBC查表结构的方法。

Java 通过JDBC查询数据库表结构(字段名称,类型,长度等)

在JDBC中,PreparedStatement.executeQuery().getMetaData();后,我们可以通过ResultSetMetaData对象查询返回结果集的源数据信息,也就是表结构信息。

示例代码如下:

package astar.sutil.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**  
* @author 鲁炬
*
*/
public class DbMetaDataUtilTest {

  public static void main(String[] args) throws SQLException, ClassNotFoundException {
    String user = "user";
    String password = "pwd";
    String jdbcDriver = "com.ibm.db2.jcc.DB2Driver";
    String jdbcUrl = "jdbc:db2://localhost:50000/DBNAME";
    Connection conn = null;
    Class.forName(jdbcDriver);
    conn = DriverManager.getConnection(jdbcUrl, user, password);

    PreparedStatement pst = null;
    try {
      pst = conn.prepareStatement("select * from t_table where 1=2");
      ResultSetMetaData rsd = pst.executeQuery().getMetaData();
      for(int i = 0; i < rsd.getColumnCount(); i++) {
        System.out.print("java类型:"+rsd.getColumnClassName(i + 1));
        System.out.print("  数据库类型:"+rsd.getColumnTypeName(i + 1));
        System.out.print("  字段名称:"+rsd.getColumnName(i + 1));
        System.out.print("  字段长度:"+rsd.getColumnDisplaySize(i + 1));
        System.out.println();
      }
    } catch(SQLException e) {
      throw new RuntimeException(e);
    } finally {
      try {
        pst.close();
        pst = null;
      } catch(SQLException e) {
        throw new RuntimeException(e);
      }
    }

  }

}



以上代码运行打印如下:

java类型:java.lang.String  数据库类型:VARCHAR  字段名称:CORP_CODE  字段名称:20
java类型:java.lang.String  数据库类型:VARCHAR  字段名称:CORP_NAME  字段名称:100
java类型:java.lang.String  数据库类型:VARCHAR  字段名称:SIMPLY_NAME  字段名称:50
java类型:java.lang.String  数据库类型:CHAR  字段名称:CORP_LEVEL  字段名称:1
java类型:java.lang.String  数据库类型:VARCHAR  字段名称:SUP_CORP_CODE  字段名称:20
java类型:java.lang.String  数据库类型:VARCHAR  字段名称:PROVINCE  字段名称:8
java类型:java.lang.String  数据库类型:VARCHAR  字段名称:STAT_CODE  字段名称:8
java类型:java.lang.String  数据库类型:CHAR  字段名称:CORP_KIND  字段名称:4
java类型:java.lang.String  数据库类型:CHAR  字段名称:IS_LEAF  字段名称:1
java类型:java.lang.String  数据库类型:CHAR  字段名称:IS_USE  字段名称:1
java类型:java.lang.String  数据库类型:CHAR  字段名称:IS_UPDATE  字段名称:1
java类型:java.lang.Integer  数据库类型:SMALLINT  字段名称:ORDER_CODE  字段名称:6
java类型:java.lang.String  数据库类型:VARCHAR  字段名称:MAP_REGIE_CODE  字段名称:20
java类型:java.lang.String  数据库类型:CHAR  字段名称:IS_SUPER  字段名称:1
java类型:java.lang.Integer  数据库类型:SMALLINT  字段名称:DISPLAY_ID  字段名称:6
java类型:java.lang.String  数据库类型:CHAR  字段名称:IS_GIS  字段名称:1


更多详细的属性输出可以读一下ResultSetMetaData对象的源码。

/*
 * @(#)ResultSetMetaData.java	1.33 05/12/01
 *
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package java.sql;

/**
 * An object that can be used to get information about the types 
 * and properties of the columns in a <code>ResultSet</code> object.
 * The following code fragment creates the <code>ResultSet</code> object rs,
 * creates the <code>ResultSetMetaData</code> object rsmd, and uses rsmd
 * to find out how many columns rs has and whether the first column in rs
 * can be used in a <code>WHERE</code> clause.
 * <PRE>
 *
 *     ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
 *     ResultSetMetaData rsmd = rs.getMetaData();
 *     int numberOfColumns = rsmd.getColumnCount();
 *     boolean b = rsmd.isSearchable(1);
 *
 * </PRE>
 */

public interface ResultSetMetaData extends Wrapper {

    /**
     * Returns the number of columns in this <code>ResultSet</code> object.
     *
     * @return the number of columns
     * @exception SQLException if a database access error occurs
     */
    int getColumnCount() throws SQLException;

    /**
     * Indicates whether the designated column is automatically numbered.
     *
     * @param column the first column is 1, the second is 2, ...
     * @return <code>true</code> if so; <code>false</code> otherwise
     * @exception SQLException if a database access error occurs
     */
    boolean isAutoIncrement(int column) throws SQLException;

    /**
     * Indicates whether a column's case matters.
     *
     * @param column the first column is 1, the second is 2, ...
     * @return <code>true</code> if so; <code>false</code> otherwise
     * @exception SQLException if a database access error occurs
     */
    boolean isCaseSensitive(int column) throws SQLException;	

    /**
     * Indicates whether the designated column can be used in a where clause.
     *
     * @param column the first column is 1, the second is 2, ...
     * @return <code>true</code> if so; <code>false</code> otherwise
     * @exception SQLException if a database access error occurs
     */
    boolean isSearchable(int column) throws SQLException;

    /**
     * Indicates whether the designated column is a cash value.
     *
     * @param column the first column is 1, the second is 2, ...
     * @return <code>true</code> if so; <code>false</code> otherwise
     * @exception SQLException if a database access error occurs
     */
    boolean isCurrency(int column) throws SQLException;

    /**
     * Indicates the nullability of values in the designated column.		
     *
     * @param column the first column is 1, the second is 2, ...
     * @return the nullability status of the given column; one of <code>columnNoNulls</code>,
     *          <code>columnNullable</code> or <code>columnNullableUnknown</code>
     * @exception SQLException if a database access error occurs
     */
    int isNullable(int column) throws SQLException;

    /**
     * The constant indicating that a
     * column does not allow <code>NULL</code> values.
     */
    int columnNoNulls = 0;

    /**
     * The constant indicating that a
     * column allows <code>NULL</code> values.
     */
    int columnNullable = 1;

    /**
     * The constant indicating that the
     * nullability of a column's values is unknown.
     */
    int columnNullableUnknown = 2;

    /**
     * Indicates whether values in the designated column are signed numbers.
     *
     * @param column the first column is 1, the second is 2, ...
     * @return <code>true</code> if so; <code>false</code> otherwise
     * @exception SQLException if a database access error occurs
     */
    boolean isSigned(int column) throws SQLException;

    /**
     * Indicates the designated column's normal maximum width in characters.
     *
     * @param column the first column is 1, the second is 2, ...
     * @return the normal maximum number of characters allowed as the width
     *          of the designated column
     * @exception SQLException if a database access error occurs
     */
    int getColumnDisplaySize(int column) throws SQLException;

    /**
     * Gets the designated column's suggested title for use in printouts and
     * displays. The suggested title is usually specified by the SQL <code>AS</code> 
     * clause.  If a SQL <code>AS</code> is not specified, the value returned from 
     * <code>getColumnLabel</code> will be the same as the value returned by the 
     * <code>getColumnName</code> method.
     *
     * @param column the first column is 1, the second is 2, ...
     * @return the suggested column title
     * @exception SQLException if a database access error occurs
     */
    String getColumnLabel(int column) throws SQLException;	

    /**
     * Get the designated column's name.
     *
     * @param column the first column is 1, the second is 2, ...
     * @return column name
     * @exception SQLException if a database access error occurs
     */
    String getColumnName(int column) throws SQLException;

    /**
     * Get the designated column's table's schema.
     *
     * @param column the first column is 1, the second is 2, ...
     * @return schema name or "" if not applicable
     * @exception SQLException if a database access error occurs
     */
    String getSchemaName(int column) throws SQLException;

    /**
     * Get the designated column's specified column size. 
     * For numeric data, this is the maximum precision.  For character data, this is the length in characters. 
     * For datetime datatypes, this is the length in characters of the String representation (assuming the 
     * maximum allowed precision of the fractional seconds component). For binary data, this is the length in bytes.  For the ROWID datatype, 
     * this is the length in bytes. 0 is returned for data types where the
     * column size is not applicable.
     *
     * @param column the first column is 1, the second is 2, ...
     * @return precision
     * @exception SQLException if a database access error occurs
     */
    int getPrecision(int column) throws SQLException;

    /**
     * Gets the designated column's number of digits to right of the decimal point.
     * 0 is returned for data types where the scale is not applicable.
     *
     * @param column the first column is 1, the second is 2, ...
     * @return scale
     * @exception SQLException if a database access error occurs
     */
    int getScale(int column) throws SQLException;	

    /**
     * Gets the designated column's table name. 
     *
     * @param column the first column is 1, the second is 2, ...
     * @return table name or "" if not applicable
     * @exception SQLException if a database access error occurs
     */
    String getTableName(int column) throws SQLException;

    /**
     * Gets the designated column's table's catalog name.
     *
     * @param column the first column is 1, the second is 2, ...
     * @return the name of the catalog for the table in which the given column
     *          appears or "" if not applicable
     * @exception SQLException if a database access error occurs
     */
    String getCatalogName(int column) throws SQLException;

    /**
     * Retrieves the designated column's SQL type.
     *
     * @param column the first column is 1, the second is 2, ...
     * @return SQL type from java.sql.Types
     * @exception SQLException if a database access error occurs
     * @see Types
     */
    int getColumnType(int column) throws SQLException;

    /**
     * Retrieves the designated column's database-specific type name.
     *
     * @param column the first column is 1, the second is 2, ...
     * @return type name used by the database. If the column type is
     * a user-defined type, then a fully-qualified type name is returned.
     * @exception SQLException if a database access error occurs
     */
    String getColumnTypeName(int column) throws SQLException;

    /**
     * Indicates whether the designated column is definitely not writable.
     *
     * @param column the first column is 1, the second is 2, ...
     * @return <code>true</code> if so; <code>false</code> otherwise
     * @exception SQLException if a database access error occurs
     */
    boolean isReadOnly(int column) throws SQLException;

    /**
     * Indicates whether it is possible for a write on the designated column to succeed.
     *
     * @param column the first column is 1, the second is 2, ...
     * @return <code>true</code> if so; <code>false</code> otherwise
     * @exception SQLException if a database access error occurs
     */
    boolean isWritable(int column) throws SQLException;

    /**
     * Indicates whether a write on the designated column will definitely succeed.	
     *
     * @param column the first column is 1, the second is 2, ...
     * @return <code>true</code> if so; <code>false</code> otherwise
     * @exception SQLException if a database access error occurs
     */
    boolean isDefinitelyWritable(int column) throws SQLException;

    //--------------------------JDBC 2.0-----------------------------------

    /**
     * <p>Returns the fully-qualified name of the Java class whose instances 
     * are manufactured if the method <code>ResultSet.getObject</code>
     * is called to retrieve a value 
     * from the column.  <code>ResultSet.getObject</code> may return a subclass of the
     * class returned by this method.
     *
     * @param column the first column is 1, the second is 2, ...
     * @return the fully-qualified name of the class in the Java programming
     *         language that would be used by the method 
     * <code>ResultSet.getObject</code> to retrieve the value in the specified
     * column. This is the class name used for custom mapping.
     * @exception SQLException if a database access error occurs
     * @since 1.2
     */
    String getColumnClassName(int column) throws SQLException;
}


如何从jdbc中获取数据库建表语句信息(字段名称/表字段类型/表字段注释信息/表字段长度等等) * 如何从jdbc中获取数据库建表语句信息(字段名称/表字段类型/表字段注释信息/表字段长度等等) * 1,表字段名称 * 2,表字段类型 * 3,表字段注释信息 这里介绍3种方式,如下: 第一种方式:执行sql语句获取 select * from user_pop_info where 1 = 2 第二种方式:执行sql语句获取 show create table user_pop_info 第二种方式:直接从jdbc数据库连接Connection实例中获取 三种方式获取的数据有一些区... 阅读详情

相关推荐

JAVA开发小技巧】JDBC批量获取数据库名、字段名、字段类型和注释信息

当我们在项目中遇到以下需求:1.给定数据库,遍历获取出数据库下的数据表名;2.给定数据表,遍历获取出表中的所有字段,对应的字段名、字段注释、字段类型等信息;使用JAVA原装的JDBC就能简单地实现以上的需求。大家想必也用过EasyCode这个十分简单方便的插件,其实它的底层就是用原装的JDBC来实现的。

funnyCaoC的博客 2019

java连接数据库的查询方法(一个方法查任意表,任意字段

今天我就来教大家如何只写一个查询方法就可以查询所有的表,并且可以添加任何条件。

qq_60614034的博客 6646

基于ESP32的气象雷达站设计与实现

物联网技术通过嵌入式设备实现环境数据的实时采集与可视化,其中ESP32凭借其双核处理器和WiFi/蓝牙功能成为热门选择。本项目利用ESP32结合LVGL图形库,构建了一个低成本气象监测系统,通过OpenWeatherMap API获取全球气象数据并在7英寸触摸屏上动态展示。系统采用三级优化策略处理高分辨率雷达图,包括服务端预处理、硬件加速解码和显示增强,有效解决了内存占用和帧率问题。在物联网设备开发中,类似方案可应用于智能家居、农业监测等场景,特别是需要实时数据可视化的领域。通过SPIFFS存储和zlib压

weixin_42524864的博客 408

jdbc 获取 表中 字段长度

参考: 使用JDBC连接数据库获取表字段的注释信息:https://my.oschina.net/Thinkeryjgfn/blog/169384   在实现一个代码生成器的时候,遇到过一个问题,需要输出字段长度 然后发现数字类型字段,无符号的会少一个长度,百度 goole半天,没搞明白怎么去判断字段,是不是无符号的类型,当时就搁置在一边了   今天在使用代码生成器时突然发现了一个...

zx1323的博客 4918

Java】如何用Java实现数据库查询

首先要创建需要查询的文件在你的文件里。记住路径,需要用文件流来找到这个文件,我的文本创建如下: import java.io.*; import java.util.*; public class DAO { //通过学生姓名找到学生学号 private String findSnumBySname(String Sname) { String result

hei我在这 2万+

通过jdbc获取数据库中的表结构 主键 各个表字段类型及应用生成实体类

  1、JDBC中通过MetaData来获取具体的表的相关信息。可以查询数据库中的有哪些表,表有哪些字段字段的属性等等。MetaData中通过一系列getXXX函数,将这些信息存放到ResultSet里面,然后返回给用户。关于MetaData的说明网上也有不少,这里我只是从我自身学习的角度来记录一下简单使用JDBC以及获取数据表相关信息的方法。 DatabaseMetaData...

anwenzhao0749的博客 440

jdbc获取mysql表数据类型_通过jdbc获取数据库中的表结构 主键 各个表字段类型及应用生成实体类...

http://www.cnblogs.com/lbangel/p/3487796.html1、JDBC中通过MetaData来获取具体的表的相关信息。可以查询数据库中的有哪些表,表有哪些字段字段的属性等等。MetaData中通过一系列getXXX函数,将这些信息存放到ResultSet里面,然后返回给用户。关于MetaData的说明网上也有不少,这里我只是从我自身学习的角度来记录一下简单使用JD...

weixin_30726605的博客 1601

jdbc获取mysql数据库表数据_通过jdbc获取数据库中的表结构

1、JDBC中通过MetaData来获取具体的表的相关信息。可以查询数据库中的有哪些表,表有哪些字段字段的属性等等。MetaData中通过一系列getXXX函数,将这些信息存放到ResultSet里面,然后返回给用户。关于MetaData的说明网上也有不少,这里我只是从我自身学习的角度来记录一下简单使用JDBC以及获取数据表相关信息的方法。DatabaseMetaData dbmd = con....

weixin_31317351的博客 1569

java程序通过JDBC连接查询数据库表名、字段类型长度、约束等

java程序通过JDBC连接查询数据库表名、字段类型长度、约束等。

weixin_70044963的博客 1162

通过jdbc获取数据库中的表结构

通过jdbc获取数据库中的表结构 主键 各个表字段类型及应用生成实体类   1、JDBC中通过MetaData来获取具体的表的相关信息。可以查询数据库中的有哪些表,表有哪些字段字段的属性等等。MetaData中通过一系列getXXX函数,将这些信息存放到ResultSet里面,然后返回给用户。关于MetaData的说明网上也有不少,这里我只是从我自身学习的角度来记录一下简单使用J...

weixin_30486037的博客 533

java基础】JDBC是啥?有啥用?

JDBC、SQL、Mysql三者的关系是: 概念 (1)JDBC连接数据库的步骤 1、加载数据库驱动,运用的是Class类的forName()静态方法来加载驱动。对,你没看错,这就是用的java反射。 2、通过DriverManager获取数据库连接。 3、通过Connection对象创建Statement对象。 4、使用Statement执行sql语句。 5、操作结果集 6、回收数据库资源 co...

玫瑰与鹿° 2505
上一篇: 面向对象思维
下一篇: 假如开源项目创始人去世了,项目怎么办? - 知乎精华
iteye_21202
博客等级 码龄8年 142粉丝 0原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值