Detailed metadata database based on the operation (operation of original data class)

1 Introduction

    In the JDBC specification, provided Connection, Statement, ResultSet three development process frequently used interface. Provide for the appropriate interface description object for each interface, JDBC specification, which is xxxMetaData series describe the object. DatabaseMetaData and ResultSetMetaData are two commonly used to obtain database metadata information interface, this article explains only method to obtain metadata DatabaseMetaData interface.

2. DatabaseMetaData Interface commonly used methods:

(1) ResultSet getTables (String catalog, String schemaPattern, String tableNamePattern, String [] types); // Get information table

(2) ResultSet getPrimaryKeys (String catalog, String schema, String table); // Get the primary key information table

(3) ResultSet getIndexInfo (String catalog, String schema, String table, boolean unique, boolean approximate); // table index information obtaining

(4) ResultSet getColumns (String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern); // Get information listed

3. Demo Package Demo:

package com.util;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import oracle.jdbc.driver.OracleConnection;

/**
* @Description: JDBC操作元数据示例-- DatabaseMetaData接口
* @CreateTime: 2014-1-19 下午9:46:44
* @author: chenzw
* @version V1.0
*/
public class JdbcUtil {
//获得驱动
private static String DRIVER = "oracle.jdbc.driver.OracleDriver";
//获得url
the URL of static String = Private "jdbc: the Oracle: Thin: @localhost: the Test";
// get connection to the database user name
Private static String the USER = "root";
// get connection to the database password
private static String PASS = "root" ;

static {
the try {
// initialize JDBC driver loaded into the drive and make the jvm
the Class.forName (the dRIVER);
} the catch (a ClassNotFoundException E) {
e.printStackTrace ();
}
}

public static Connection the getConnection () {
Connection Conn = null ;
the try {
// connect to the database

/ *
* REMARK remark information available provided
the Properties The props = new new the Properties ();
props.put ( "remarksReporting", "to true");
props.put ( "User", the USER);
The props. put ( "password",PASS);
conn =DriverManager.getConnection(URL,props);*/

conn = DriverManager.getConnection(URL,USER,PASS);
conn.setAutoCommit(true);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}

//关闭连接
public static void close(Object o){
if (o == null){
return;
}
if (o instanceof ResultSet){
try {
((ResultSet)o).close();
} catch (SQLException e) {
e.printStackTrace();
}
} else if(o instanceof Statement){
try {
((Statement)o).close();
} catch (SQLException e) {
e.printStackTrace();
}
} else if (o instanceof Connection){
Connection c = (Connection)o;
try {
if (!c.isClosed()){
c.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}


public static void close(ResultSet rs, Statement stmt,
Connection conn){
close(rs);
close(stmt);
close(conn);
}

public static void close(ResultSet rs,
Connection conn){
close(rs);
close(conn);
}



/**
* @Description: 获取数据库相关信息
* @author: chenzw
* @CreateTime: 2014-1-27 下午5:09:12
* @throws
*/
static void getDatabaseInfo public () {
Connection Conn = the getConnection ();
the ResultSet RS = null;
the try {
the DatabaseMetaData DBMD conn.getMetaData = ();
System.out.println ( "Database known user:" + dbmd.getUserName () );
System.out.println ( "comma-separated list of the database system functions:" + dbmd.getSystemFunctions ());
System.out.println ( "time and date functions comma-separated list of databases:" + dbmd.getTimeDateFunctions ());
System.out.println ( "comma-separated list of strings database functions:" + dbmd.getStringFunctions ());
System.out.println ( "database for the vendor 'schema' preferred term:" + dbmd.getSchemaTerm ());
System.out.println ( "database the URL:" + dbmd.getURL ());
System.out.println ( "allow read only:" + dbmd.isReadOnly ());
the System.out .println ( "database product name:" + dbmd.getDatabaseProductName());
System.out.println ( "Database version:" + dbmd.getDatabaseProductVersion ());
System.out.println ( "Driver's name:" + dbmd.getDriverName ());
System.out.println ( "driver version: "+ dbmd.getDriverVersion ());

System.out.println (" sheet type "is used in the database);
RS = dbmd.getTableTypes ();
the while (rs.next ()) {
System.out.println (rs.getString ( "TABLE_TYPE"));
}
} the catch (SQLException E) {
e.printStackTrace ();
} {the finally
JdbcUtil.close (RS, Conn);
}
}

/ **
* @Description: obtaining all the database schemas (corresponding to the oracle the Tablespace)
* @author: chenzw
* @CreateTime: 2014-1-27 5:10 pm:35
* @throws
*/
public static void getSchemasInfo(){
Connection conn = getConnection();
ResultSet rs = null;
try{
DatabaseMetaData dbmd = conn.getMetaData();
rs = dbmd.getSchemas();
while (rs.next()){
String tableSchem = rs.getString("TABLE_SCHEM");
System.out.println(tableSchem);
}
} catch (SQLException e){
e.printStackTrace();
} finally{
JdbcUtil.close(rs,conn);
}
}

/**
* @Description: 获取数据库中所有的表信息
* @author: chenzw
* @CreateTime: 2014-1-27 下午5:08:28
* @throws
*/
public static void getTablesList() {
Connection conn = getConnection();
ResultSet rs = null;
try {
/**
* 设置连接属性,使得可获取到表的REMARK(备注)
*/
((OracleConnection)conn).setRemarksReporting(true);
DatabaseMetaData dbmd = conn.getMetaData();
String[] types = { "TABLE" };
rs = dbmd.getTables(null, null, "%", types);
while (rs.next()) {
String tableName = rs.getString("TABLE_NAME"); //表名
String tableType = rs.getString("TABLE_TYPE"); //表类型
String remarks = rs.getString("REMARKS"); //表备注
System.out.println(tableName + " - " + tableType + " - " + remarks);
}
} catch (SQLException e) {
e.printStackTrace();
} finally{
JdbcUtil.close(rs,conn);* @Description: Get a list of information/ **}
}




@Author *: chenzw
* @CreateTime: 2014-1-27 PM 3:26:30
* @throws
* /
public static void getTablesInfo () {
Connection Conn = the getConnection ();
the ResultSet RS = null;
the try {
/ **
* set the connection properties, so that the table can be acquired REMARK (Note)
* /
((the OracleConnection) Conn) .setRemarksReporting (to true);
the DatabaseMetaData DBMD conn.getMetaData = ();
/ **
* Get a given category table used description.
* Prototype method: ResultSet getTables in (Cataog String, String schemaPattern, tableNamePattern String, String [] types);
* Cataog - category where the name of the table; "" retrieves no category column, null retrieves column all categories.
* Schema - mode where the name of the table (oracle corresponding to the Tablespace); "" retrieves no pattern columns, column null identifier obtaining all patterns; may comprise a single wildcard character ( "_"), or a wildcard character ( " % ");
* TableNamePattern - table name; may comprise a single wildcard character ( "_"), or wildcard characters ( "%");
* types - type array table; "TABLE", "VIEW" , "SYSTEM TABLE", "GLOBAL TEMPORARY "," LOCAL TEMPORARY "," ALIAS " and" SYNONYM "; null represents include all types of tables; may comprise a single wildcard character (" _ "), or wildcard characters ("% ");
* /
RS = DBMD. getTables in (null, null, "CUST_INTER_TF_SERVICE_REQ", new new String [] { "tABLE", "the VIEW"});


the while (rs.next ()) {
String tableCat = rs.getString ( "TABLE_CAT"); // table catalog (can be null)
String tableSchemaName rs.getString = ( "TABLE_SCHEM"); // table mode (possibly empty), acquired in the oracle namespace, other databases unknown
String tableName = rs.getString ( "TABLE_NAME" ) ; // table name
String tableType = rs.getString ( "TABLE_TYPE" ); // table type,典型的类型是 "TABLE"、"VIEW"、"SYSTEM TABLE"、"GLOBAL TEMPORARY"、"LOCAL TEMPORARY"、"ALIAS" 和 "SYNONYM"。
String remarks = rs.getString("REMARKS"); //表备注

System.out.println (tableCat + "-" + tableSchemaName + "-" + tableName + "-" + TABLETYPE + "-"
+ Remarks);
}
} the catch (Exception EX) {
ex.printStackTrace ();
} {the finally
JdbcUtil.close (RS, Conn);
}
}

/ **
* @Description: primary key information acquiring
* @author: chenzw
* @CreateTime: 2014-1-27 PM 5:12:53
* @throws
* /
public static void getPrimaryKeysInfo () {
Connection Conn = the getConnection ();
the ResultSet RS = null;
the try {
the DatabaseMetaData DBMD conn.getMetaData = ();
/ **
* for a description of the given table's primary key column
* method prototype: ResultSet getPrimaryKeys (String catalog , String schema, String table);
* Catalog - category where the name of the table; "" retrieves no category column, null retrieves column all categories.
* Schema - mode where the name of the table (oracle corresponding to the Tablespace); "" retrieves no pattern columns, column null identifier obtaining all patterns; may comprise a single wildcard character ( "_"), or a wildcard character ( " % ");
* table - table name; may comprise a single wildcard character (" _ "), or wildcard characters ("% ");
* /
RS = DBMD.getPrimaryKeys (null, null," CUST_INTER_TF_SERVICE_REQ ");

the while ( rs.next ()) {
String tableCat rs.getString = ( "TABLE_CAT"); // table catalog (can be null)
String tableSchemaName rs.getString = ( "TABLE_SCHEM"); // table mode (possibly empty), oracle is acquired in a namespace, other databases unknown
String tableName = rs.getString ( "TABLE_NAME" ); // table name
String columnName = rs.getString ( "COLUMN_NAME" ); // column names
short keySeq = rs.getShort ( "KEY_SEQ");


System.out.println (tableCat + "-" + tableSchemaName + "-" + tableName + "-" columnName + + "-"
+ keyseq + "-" + pkName);
}
} the catch (SQLException E) {
e.printStackTrace ();
} {the finally
JdbcUtil.close (RS, Conn);
}
}

/ **
* @Description: an acquisition table index information
* @author: chenzw
* @CreateTime: 2014-1-27 5:12:04 PM
* @ throws
* /
public static void getIndexInfo () {
Connection Conn = the getConnection ();
the ResultSet RS = null;
{the try
the DatabaseMetaData DBMD conn.getMetaData = ();
/ **
description index and obtaining statistical information given table *
* Prototype method: ResultSet getIndexInfo (Cataog String, String Schema, the Table String, boolean UNIQUE, boolean Approximate)
* Cataog - category where the name of the table; "" retrieves no category column, null retrieves column all categories.
* Schema - mode where the name of the table (oracle corresponding to the Tablespace); "" retrieves no pattern columns, column null identifier obtaining all patterns; may comprise a single wildcard character ( "_"), or a wildcard character ( " % ");
* table - table name; may comprise a single wildcard character (" _ "), or wildcard characters ("% ");
* uNIQUE - this parameter is true, return only unique index value; this parameter is when false, returns all indexes;
* Approximate - this parameter is true, the result is a value other than the allowed data value or a close of the data values; this parameter is false, the result is accurate results required;
* /
RS = dbmd.getIndexInfo (null, null, "CUST_INTER_TF_SERVICE_REQ", to false, to true);
the while (rs.next ()) {
String tableCat rs.getString = ( "TABLE_CAT"); // table catalog (can be null)
String tableSchemaName = rs.getString ( "TABLE_SCHEM");
String tableName = rs.getString ( "TABLE_NAME" ); // table
boolean nonUnique = rs.getBoolean ( "NON_UNIQUE" ); // if index values may not be unique, TYPE is tableIndexStatistic index value to false;
String = RS indexQualifier .getString ( "INDEX_QUALIFIER"); // index categories (possibly empty), TYPE index is tableIndexStatistic category is null;
String indexName = rs.getString ( "INDEX_NAME"); // name of the index; TYPE index is tableIndexStatistic name is null;
/ **
* index types:
* tableIndexStatistic - this index identifies and describes the return table with table statistics
* tableIndexClustered - this is a clustered index
* tableIndexHashed - this is a hashed index
* tableIndexOther - this is some other style index
* /
Short type = rs.getShort ( "the tYPE"); // index type;
Short OrdinalPosition = rs.getShort ( "the ORDINAL_POSITION"); // in the index column sequence number; the serial number of the tYPE is tableIndexStatistic zero;
String columnName = rs.getString ( "COLUMN_NAME" ); // column name; tableIndexStatistic when the TYPE column name is null;
String ascOrDesc = rs.getString ( "ASC_OR_DESC"); // column sort order: ascending or descending [A: ascending; B: descending]; if not supported collating sequence, possibly null; tableIndexStatistic TYPE ordered sequence is null;
int = rs.getInt with cardinality ( "the cARDINALITY"); // base; tableIndexStatistic when TYPE is, it is the number of rows in the table; otherwise, it is the number of unique values in the index.
int pages = rs.getInt ( "PAGES" ); // TYPE is when tableIndexStatisic, it is the number of pages for the table, otherwise it is the number of pages for the current index.
String filterCondition = rs.getString ( "FILTER_CONDITION" ); // filter conditions, if any (possibly null).

System.out.println (tableCat + "-" + tableSchemaName + "-" + tableName + "-" + nonunique + "-"
+ indexQualifier + "-" + indexName + "-" + + of the type "-"
+ "-" + ascOrDesc + "-" + with cardinality + "-" + Pages + "-" + FilterCondition);
}
} the catch (SQLException E) {
e.printStackTrace ();
} {the finally
JdbcUtil.close (RS, Conn );
}
}


/ **
* @Description: obtaining information table column values
* @author: chenzw
* @CreateTime: 2014-1-27 PM 2:55:56
* @throws
* /
public static void getColumnsInfo () {
Connection = the getConnection Conn ();
the ResultSet RS = null;

the try {
/ **
* set the connection properties, making it possible to obtain the REMARK (Note) column
* /
((the OracleConnection) Conn) .setRemarksReporting (to true);
the DatabaseMetaData DBMD = Conn. getMetaData ();
/ **
* Retrieves a description of table columns can be used in the specified category.
* Prototype method: ResultSet getColumns (Cataog String, String schemaPattern, tableNamePattern String, String columnNamePattern)
* Cataog - category where the name of the table; "" retrieves no category column, null retrieves column all categories.
* Schema - mode where the name of the table (oracle corresponding to the Tablespace); "" retrieves no pattern columns, column null identifier obtaining all patterns; may comprise a single wildcard character ( "_"), or a wildcard character ( " % ");
* tableNamePattern - table name; may comprise a single wildcard character (" _ "), or wildcard characters ("% ");
* columnNamePattern - column name;" "retrieves column named" "column (of course Get less); null retrieves all columns; may comprise a single wildcard character ( "_"), or wildcard characters ( "%");
* /
RS = DBMD.getColumns (null, null, "CUST_INTER_TF_SERVICE_REQ", null );

the while (rs.next ()) {
String tableCat rs.getString = ( "TABLE_CAT"); // table catalog (possibly empty)
String tableSchemaName rs.getString = ( "TABLE_SCHEM"); // table mode (possible Is empty),

String columnName = rs.getString ( "COLUMN_NAME" ); // column name
int dataType = rs.getInt ( "DATA_TYPE" ); SQL types (column type ID) // java.sql.Types corresponding to the
String dataTypeName = rs. getString ( "TYPE_NAME"); //java.sql.Types type name (type name column)
int = rs.getInt ColumnSize ( "COLUMN_SIZE"); // column size
int decimalDigits = rs.getInt ( "DECIMAL_DIGITS" ); / / decimal
int numPrecRadix = rs.getInt ( "NUM_PREC_RADIX" ); // base (typically 2 or 10) - unknown
/ **
* 0 (columnNoNulls) - does not allow the column is empty
* 1 (columnNullable) - this column allows null
* 2 (columnNullableUnknown) - unsure whether the column is empty
* /
int Nullable = rs.getInt ( "NULLABLE"); // whether to allow null
String Remarks = rs.getString ( "REMARKS for"); // column description
String columnDef = rs.getString ( "COLUMN_DEF "); // default values
int charOctetLength = rs.getInt ( "CHAR_OCTET_LENGTH" ); // for char type, this length is the maximum number of bytes in the column
int ordinalPosition = rs.getInt ( "ORDINAL_POSITION" ); // index table column (from 1 start)
/ **
* the ISO rules to determine if a column may be empty (equivalent to the value of nULLABLE: [0: 'YES';. 1: 'NO'; 2: '';])
* YES - the column can nulls;
* nO - the column can not be empty;
* --- empty string can not know whether the column is empty
* /
string IsNullable = rs.getString ( "IS_NULLABLE");

/ **
* indicates whether this column is automatically incremented
* YES - this column is auto incremented
* NO - this column is not automatically increments
* empty string --- can not determine whether the column automatically increments
* /
// String isAutoIncrement = rs.getString ( "IS_AUTOINCREMENT"); // this parameter test given


System.out.println (tableCat + "-" + tableSchemaName + "-" + tableName_ + "-"+ columnName +
" - " + dataType + " - " + dataTypeName + " - " + columnSize + " - " + decimalDigits + " - "
+ numPrecRadix + " - " + nullAble + " - " + remarks + " - " + columnDef + " - " + charOctetLength
+ " - " + ordinalPosition + " - " + isNullAble );

}
}catch(SQLException ex){
ex.printStackTrace();
}finally{
JdbcUtil.close(rs,conn);
}
}

/**
* @Description: TODO
* @author: chenzw
* @CreateTime: 2014-1-17 下午2:47:45
* @param args
* @throws
*/
public static void main(String[] args) {
getDataBaseInfo();// get database information getTablesList (); // get all the tables under a user
getSchemasInfo (); // get a database of all the Schema

getTablesInfo (); // table information obtaining
getPrimaryKeysInfo (); // table primary key information acquiring
getIndexInfo (); // table index information obtaining
getColumnsInfo (); // table column values acquired information
}
}
 
------- ---------
Disclaimer: this article is CSDN blogger "lncdzh 'original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
Original link: https: //blog.csdn.net/lncdzh/article/details/78723237

Guess you like

Origin www.cnblogs.com/hongjiahui/p/11848155.html