• 使用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("
    ");
    
    
        }
    }

    执行结果

  • 相关阅读:
    开机自动挂载分区
    Wine安装
    ubuntu 将idea/vscode快捷方式加入到启动器中
    在Linux上安装Java
    httpclient
    shiro
    redis-随笔
    maven
    spring的aop
    spring事务知识梳理
  • 原文地址:https://www.cnblogs.com/yeyongjian/p/8972516.html
Copyright © 2020-2023  润新知