java|java 通过数据库名获得 该数据所有的表名以及字段名、字段类型

package com.nf.lc.sql_meta_data; import java.sql.*; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * 获得数据库表的元数据 */ public class GetSQLMetaData {public static void main(String[] args) throws SQLException, ClassNotFoundException {HashMap computer_mall = (HashMap) getDatabaseNameToTableNameAndColumnName("computer_mall"); Set tableNames = computer_mall.keySet(); System.out.println("一共有表:" + tableNames.size() + "张"); for (String tableName : tableNames) { System.out.println("===========================\r\n"); System.out.println("表名:" + tableName); // <字段名,类型>HashMap 集合 HashMap columnNames = (HashMap) computer_mall.get(tableName); Set columns = columnNames.keySet(); for (String column : columns) { System.out.println("字段名:" + column + " 类型:" + columnNames.get(column)); }System.out.println("===========================\r\n"); }}public static Map getDatabaseNameToTableNameAndColumnName(String databaseName) throws SQLException, ClassNotFoundException {String driver = "org.mariadb.jdbc.Driver"; String url = "jdbc:mariadb://localhost:3306/" + databaseName; String username = "root"; String password = "root"; Map tableNameMap = new HashMap<>(); //加载驱动 Class.forName(driver); //获得数据库连接 Connection connection = DriverManager.getConnection(url, username, password); //获得元数据 DatabaseMetaData metaData = https://www.it610.com/article/connection.getMetaData(); //获得表信息 ResultSet tables = metaData.getTables(null, null, null, new String[]{"TABLE"}); while (tables.next()) { Map columnNameMap = new HashMap<>(); //保存字段名//获得表名 String table_name = tables.getString("TABLE_NAME"); //通过表名获得所有字段名 ResultSet columns = metaData.getColumns(null, null, table_name, "%"); //获得所有字段名 while (columns.next()) { //获得字段名 String column_name = columns.getString("COLUMN_NAME"); //获得字段类型 String type_name = columns.getString("TYPE_NAME"); columnNameMap.put(column_name, type_name); }tableNameMap.put(table_name, columnNameMap); }return tableNameMap; }}


关于获得数据库相关信息:

String driver = "org.mariadb.jdbc.Driver"; String url = "jdbc:mariadb://localhost:3306/" + databaseName; String username = "root"; String password = "root"; //加载驱动 Class.forName(driver); //获得数据库连接 Connection connection = DriverManager.getConnection(url, username, password); //获得元数据 DatabaseMetaData metaData = https://www.it610.com/article/connection.getMetaData(); //获得数据库名称 String databaseProductName = metaData.getDatabaseProductName(); //获得数据库版本号 String databaseProductVersion = metaData.getDatabaseProductVersion(); //获得数据库用户名 String userName = metaData.getUserName(); //获得数据库连接URL String jdbcUrl = metaData.getURL(); //获得数据库驱动 String driverName = metaData.getDriverName(); //获得数据库驱动版本号 String driverVersion = metaData.getDriverVersion();






归途(LC)

【java|java 通过数据库名获得 该数据所有的表名以及字段名、字段类型】转载于:https://www.cnblogs.com/ldl326308/p/10279162.html

    推荐阅读