JDBC 读取数据库中的表信息和字段信息

来源:互联网 发布:js按键事件 编辑:程序博客网 时间:2024/06/05 12:26

一、获取Connection

    public static Connection getConnect() {        Connection con = null;        try {            Class.forName("org.postgresql.Driver");            con = DriverManager.getConnection(url, name, password);        } catch (Exception e) {            e.printStackTrace();        }        return con;    }

二、获取表信息和列信息

try {            Connection con = getConnect();            DatabaseMetaData metaData = con.getMetaData();            ResultSet resultSet = metaData.getTables(null, "%", "%", new String[] { "TABLE" });            while (resultSet.next()) {                String tableName = resultSet.getString("TABLE_NAME");                if ("tb_sm_module".equals(tableName)) {                    ResultSet resultCol = metaData.getColumns(null, "%", tableName, "%");                    while (resultCol.next()) {                        String columnName = resultCol.getString("COLUMN_NAME");                        String columnType = resultCol.getString("TYPE_NAME");                        int datasize = resultCol.getInt("COLUMN_SIZE");                        int digits = resultCol.getInt("DECIMAL_DIGITS");                        int nullable = resultCol.getInt("NULLABLE");                        System.out.println(columnName + " " + columnType + " " + datasize + " " + digits + " " + nullable);                    }                }            }        } catch (SQLException e) {            e.printStackTrace();        }

三、获取主键信息

ResultSet pkRSet = metaData.getPrimaryKeys(null, null, tableName); while (pkRSet.next()) {    pkRSet.getString("COLUMN_NAME");}
0 0