• 使用JDBC connect获取数据库表结构信息


    1、这是生成代码的关键

    引入maven依赖

       <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.30</version>
            </dependency>

    2、编写JAVA类

    package com.yyj.mybties.jdbc;
    
    
    import java.sql.Connection;
    import java.sql.DatabaseMetaData;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * 获取数据库中表的结构
     */
    public class JDBCdemo {
        public static void main(String[] args) {
        String driver = "com.mysql.jdbc.Driver";
        String URL = "jdbc:mysql://localhost:3306/mybase";
        Connection con = null;
        List<String> tableNames = new ArrayList();
        try {
            con= DriverManager.getConnection(URL,"root","");
            getTableInfo(con,"users");
        } catch(Exception e) {
            System.out.println("Connect fail:" + e.getMessage());
        }
    }
        private static void getTableInfo(Connection con,String tableName) throws SQLException {
            DatabaseMetaData metaData = con.getMetaData();
            ResultSet colRet = metaData.getColumns(null, "%", tableName, "%");
            String columnName;
            String columnType;
            while(colRet.next()){
                columnName = colRet.getString("COLUMN_NAME");
                columnType = colRet.getString("TYPE_NAME");
                int datasize = colRet.getInt("COLUMN_SIZE");
                int digits = colRet.getInt("DECIMAL_DIGITS");
                int nullable = colRet.getInt("NULLABLE");
                System.out.println(columnName+" "+columnType+" "+datasize+" "+digits+" "+ nullable);
            }
            System.out.println("
    ");
    
    
        }
    }

    执行结果

  • 相关阅读:
    hadoop2.2编程:MRUnit测试
    TestLinkConverter编程纪要
    Redisson的分布式锁的简单实现
    Jmeter工具使用
    JVM的学习(三)
    Mybatis需要注意的地方及知识点
    JVM学习二(JAVA的四种引用)
    mysql的引擎
    JVM学习一(JVM的内存结构和垃圾回收)
    JDk1.8HashMap的源码分析
  • 原文地址:https://www.cnblogs.com/yeyongjian/p/8972516.html
Copyright © 2020-2023  润新知