Java简单读取MYSQL表名、字段和属性

【完整代码在最后】

Maven的pom.xml中添加Mysql依赖

        
        
            mysql
            mysql-connector-java
            8.0.23
        

新建类,创建主类,导入包

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;

第一步,配置连接信息

        String url = "jdbc:mysql://你的地址/你的数据库";
        String user = "root";
        String password = "pwd";

第二步,通过信息连接数据库

            Connection connection = DriverManager.getConnection(url, user, password);

            DatabaseMetaData metaData = connection.getMetaData();
            ResultSet columns = metaData.getColumns(null, null, "Users", null);

第三步,输出表字段

            while (columns.next()) {
                String columnName = columns.getString("COLUMN_NAME");
                String columnType = columns.getString("TYPE_NAME");
                int columnSize = columns.getInt("COLUMN_SIZE");

                System.out.println("字段名: " + columnName);
                System.out.println("字段类型: " + columnType);
                System.out.println("最大长度: " + columnSize);
                System.out.println("-------------");
            }

第四步,关闭连接

            connection.close();

完整代码

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;

public class read_table_c_length {
    public static void main(String[] args) {
        String url = "jdbc:mysql://地址/数据库";
        String user = "root";
        String password = "pwd";

        try {
            Connection connection = DriverManager.getConnection(url, user, password);

            DatabaseMetaData metaData = connection.getMetaData();
            ResultSet columns = metaData.getColumns(null, null, "Users", null);

            while (columns.next()) {
                String columnName = columns.getString("COLUMN_NAME");
                String columnType = columns.getString("TYPE_NAME");
                int columnSize = columns.getInt("COLUMN_SIZE");

                System.out.println("字段名: " + columnName);
                System.out.println("字段类型: " + columnType);
                System.out.println("最大长度: " + columnSize);
                System.out.println("-------------");
            }

            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

你可能感兴趣的:(java,mysql,adb)