java獲得數據庫信息常用API(DatabaseMetaData)示例

最近要做一個數據字典的工具,看了一下DatabaseMetaData的使用,做個備忘示例!

Java代碼 複製代碼
  1. package com.database.manager;   
  2.   
  3. import java.sql.Connection;   
  4. import java.sql.DatabaseMetaData;   
  5. import java.sql.DriverManager;   
  6. import java.sql.ResultSet;   
  7. import java.sql.SQLException;   
  8.   
  9. /**  
  10.  * @author daoger  
  11.  *   
  12.  * 2009-9-24  
  13.  */  
  14. public class DatabaseMetaDateApplication   
  15. {   
  16.     private DatabaseMetaData dbMetaData = null;   
  17.   
  18.     private Connection con = null;   
  19.   
  20.     private void getDatabaseMetaData()   
  21.     {   
  22.         try  
  23.         {   
  24.             if (dbMetaData == null)   
  25.             {   
  26.                 Class.forName("oracle.jdbc.driver.OracleDriver");   
  27.                 String url = "jdbc:oracle:thin:@192.168.0.2:1521:×××";   
  28.                 String user = "×××";   
  29.                 String password = "×××";   
  30.                 con = DriverManager.getConnection(url, user, password);   
  31.                 dbMetaData = con.getMetaData();   
  32.             }   
  33.         } catch (ClassNotFoundException e)   
  34.         {   
  35.             // TODO: handle ClassNotFoundException   
  36.             e.printStackTrace();   
  37.         } catch (SQLException e)   
  38.         {   
  39.             // TODO: handle SQLException   
  40.             e.printStackTrace();   
  41.         }   
  42.     }   
  43.   
  44.     public void colseCon()   
  45.     {   
  46.         try  
  47.         {   
  48.             if (con != null)   
  49.             {   
  50.                 con.close();   
  51.             }   
  52.         } catch (SQLException e)   
  53.         {   
  54.             // TODO: handle SQLException   
  55.             e.printStackTrace();   
  56.         }   
  57.     }   
  58.   
  59.     /**  
  60.      * 獲得數據庫的一些相關信息  
  61.      */  
  62.     public void getDataBaseInformations()   
  63.     {   
  64.         try  
  65.         {   
  66.             System.out.println("URL:" + dbMetaData.getURL() + ";");   
  67.             System.out.println("UserName:" + dbMetaData.getUserName() + ";");   
  68.             System.out.println("isReadOnly:" + dbMetaData.isReadOnly() + ";");   
  69.             System.out.println("DatabaseProductName:" + dbMetaData.getDatabaseProductName() + ";");   
  70.             System.out.println("DatabaseProductVersion:" + dbMetaData.getDatabaseProductVersion() + ";");   
  71.             System.out.println("DriverName:" + dbMetaData.getDriverName() + ";");   
  72.             System.out.println("DriverVersion:" + dbMetaData.getDriverVersion());   
  73.         } catch (SQLException e)   
  74.         {   
  75.             // TODO: handle SQLException   
  76.             e.printStackTrace();   
  77.         }   
  78.     }   
  79.   
  80.     /**  
  81.      * 獲得該用戶下面的所有表  
  82.      */  
  83.     public void getAllTableList(String schemaName)   
  84.     {   
  85.         try  
  86.         {   
  87.             // table type. Typical types are "TABLE", "VIEW", "SYSTEM   
  88.             // TABLE", "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS",   
  89.             // "SYNONYM".   
  90.             String[] types =   
  91.             { "TABLE" };   
  92.             ResultSet rs = dbMetaData.getTables(null, schemaName, "%", types);   
  93.             while (rs.next())   
  94.             {   
  95.                 String tableName = rs.getString("TABLE_NAME");   
  96.                 // table type. Typical types are "TABLE", "VIEW", "SYSTEM   
  97.                 // TABLE", "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS",   
  98.                 // "SYNONYM".   
  99.                 String tableType = rs.getString("TABLE_TYPE");   
  100.                 // explanatory comment on the table   
  101.                 String remarks = rs.getString("REMARKS");   
  102.                 System.out.println(tableName + "-" + tableType + "-" + remarks);   
  103.             }   
  104.         } catch (SQLException e)   
  105.         {   
  106.             // TODO: handle SQLException   
  107.             e.printStackTrace();   
  108.         }   
  109.     }   
  110.   
  111.     /**  
  112.      * 獲得該用戶下面的所有視圖  
  113.      */  
  114.     public void getAllViewList(String schemaName)   
  115.     {   
  116.         try  
  117.         {   
  118.             String[] types =   
  119.             { "VIEW" };   
  120.             ResultSet rs = dbMetaData.getTables(null, schemaName, "%", types);   
  121.             while (rs.next())   
  122.             {   
  123.                 String viewName = rs.getString("TABLE_NAME");   
  124.                 // table type. Typical types are "TABLE", "VIEW", "SYSTEM   
  125.                 // TABLE", "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS",   
  126.                 // "SYNONYM".   
  127.                 String viewType = rs.getString("TABLE_TYPE");   
  128.                 // explanatory comment on the table   
  129.                 String remarks = rs.getString("REMARKS");   
  130.                 System.out.println(viewName + "-" + viewType + "-" + remarks);   
  131.             }   
  132.         } catch (SQLException e)   
  133.         {   
  134.             // TODO: handle SQLException   
  135.             e.printStackTrace();   
  136.         }   
  137.     }   
  138.   
  139.     /**  
  140.      * 獲得數據庫中所有方案名稱  
  141.      */  
  142.     public void getAllSchemas()   
  143.     {   
  144.         try  
  145.         {   
  146.             ResultSet rs = dbMetaData.getSchemas();   
  147.             while (rs.next())   
  148.             {   
  149.                 String tableSchem = rs.getString("TABLE_SCHEM");   
  150.                 System.out.println(tableSchem);   
  151.             }   
  152.         } catch (SQLException e)   
  153.         {   
  154.             // TODO: handle SQLException   
  155.             e.printStackTrace();   
  156.         }   
  157.     }   
  158.   
  159.     /**  
  160.      * 獲得表或視圖中的所有列信息  
  161.      */  
  162.     public void getTableColumns(String schemaName, String tableName)   
  163.     {   
  164.         try  
  165.         {   
  166.             ResultSet rs = dbMetaData.getColumns(null, schemaName, tableName, "%");   
  167.             while (rs.next())   
  168.             {   
  169.                 // table catalog (may be null)   
  170.                 String tableCat = rs.getString("TABLE_CAT");   
  171.                 // table schema (may be null)   
  172.                 String tableSchemaName = rs.getString("TABLE_SCHEM");   
  173.                 // table name   
  174.                 String tableName_ = rs.getString("TABLE_NAME");   
  175.                 // column name   
  176.                 String columnName = rs.getString("COLUMN_NAME");   
  177.                 // SQL type from java.sql.Types   
  178.                 int dataType = rs.getInt("DATA_TYPE");   
  179.                 // Data source dependent type name, for a UDT the type name is   
  180.                 // fully qualified   
  181.                 String dataTypeName = rs.getString("TYPE_NAME");   
  182.                 // table schema (may be null)   
  183.                 int columnSize = rs.getInt("COLUMN_SIZE");   
  184.                 // the number of fractional digits. Null is returned for data   
  185.                 // types where DECIMAL_DIGITS is not applicable.   
  186.                 int decimalDigits = rs.getInt("DECIMAL_DIGITS");   
  187.                 // Radix (typically either 10 or 2)   
  188.                 int numPrecRadix = rs.getInt("NUM_PREC_RADIX");   
  189.                 // is NULL allowed.   
  190.                 int nullAble = rs.getInt("NULLABLE");   
  191.                 // comment describing column (may be null)   
  192.                 String remarks = rs.getString("REMARKS");   
  193.                 // default value for the column, which should be interpreted as   
  194.                 // a string when the value is enclosed in single quotes (may be   
  195.                 // null)   
  196.                 String columnDef = rs.getString("COLUMN_DEF");   
  197.                 //                 
  198.                 int sqlDataType = rs.getInt("SQL_DATA_TYPE");   
  199.                 //                 
  200.                 int sqlDatetimeSub = rs.getInt("SQL_DATETIME_SUB");   
  201.                 // for char types the maximum number of bytes in the column   
  202.                 int charOctetLength = rs.getInt("CHAR_OCTET_LENGTH");   
  203.                 // index of column in table (starting at 1)   
  204.                 int ordinalPosition = rs.getInt("ORDINAL_POSITION");   
  205.                 // ISO rules are used to determine the nullability for a column.   
  206.                 // YES --- if the parameter can include NULLs;   
  207.                 // NO --- if the parameter cannot include NULLs   
  208.                 // empty string --- if the nullability for the parameter is   
  209.                 // unknown   
  210.                 String isNullAble = rs.getString("IS_NULLABLE");   
  211.                 // Indicates whether this column is auto incremented   
  212.                 // YES --- if the column is auto incremented   
  213.                 // NO --- if the column is not auto incremented   
  214.                 // empty string --- if it cannot be determined whether the   
  215.                 // column is auto incremented parameter is unknown   
  216.                 String isAutoincrement = rs.getString("IS_AUTOINCREMENT");   
  217.                 System.out.println(tableCat + "-" + tableSchemaName + "-" + tableName_ + "-" + columnName + "-"  
  218.                         + dataType + "-" + dataTypeName + "-" + columnSize + "-" + decimalDigits + "-" + numPrecRadix   
  219.                         + "-" + nullAble + "-" + remarks + "-" + columnDef + "-" + sqlDataType + "-" + sqlDatetimeSub   
  220.                         + charOctetLength + "-" + ordinalPosition + "-" + isNullAble + "-" + isAutoincrement + "-");   
  221.             }   
  222.         } catch (SQLException e)   
  223.         {   
  224.             // TODO: handle SQLException   
  225.             e.printStackTrace();   
  226.         }   
  227.     }   
  228.   
  229.     /**  
  230.      * 獲得一個表的索引信息  
  231.      */  
  232.     public void getIndexInfo(String schemaName, String tableName)   
  233.     {   
  234.         try  
  235.         {   
  236.             ResultSet rs = dbMetaData.getIndexInfo(null, schemaName, tableName, truetrue);   
  237.             while (rs.next())   
  238.             {   
  239.                 // Can index values be non-unique. false when TYPE is   
  240.                 // tableIndexStatistic   
  241.                 boolean nonUnique = rs.getBoolean("NON_UNIQUE");   
  242.                 // index catalog (may be null); null when TYPE is   
  243.                 // tableIndexStatistic   
  244.                 String indexQualifier = rs.getString("INDEX_QUALIFIER");   
  245.                 // index name; null when TYPE is tableIndexStatistic   
  246.                 String indexName = rs.getString("INDEX_NAME");   
  247.                 // index type:   
  248.                 // tableIndexStatistic - this identifies table statistics that   
  249.                 // are returned in conjuction with a table's index descriptions   
  250.                 // tableIndexClustered - this is a clustered index   
  251.                 // tableIndexHashed - this is a hashed index   
  252.                 // tableIndexOther - this is some other style of index   
  253.                 short type = rs.getShort("TYPE");   
  254.                 // column sequence number within index; zero when TYPE is   
  255.                 // tableIndexStatistic   
  256.                 short ordinalPosition = rs.getShort("ORDINAL_POSITION");   
  257.                 // column name; null when TYPE is tableIndexStatistic   
  258.                 String columnName = rs.getString("COLUMN_NAME");   
  259.                 // column sort sequence, "A" => ascending, "D" => descending,   
  260.                 // may be null if sort sequence is not supported; null when TYPE   
  261.                 // is tableIndexStatistic   
  262.                 String ascOrDesc = rs.getString("ASC_OR_DESC");   
  263.                 // When TYPE is tableIndexStatistic, then this is the number of   
  264.                 // rows in the table; otherwise, it is the number of unique   
  265.                 // values in the index.   
  266.                 int cardinality = rs.getInt("CARDINALITY");   
  267.                 System.out.println(nonUnique + "-" + indexQualifier + "-" + indexName + "-" + type + "-"  
  268.                         + ordinalPosition + "-" + columnName + "-" + ascOrDesc + "-" + cardinality);   
  269.             }   
  270.         } catch (SQLException e)   
  271.         {   
  272.             // TODO: handle SQLException   
  273.             e.printStackTrace();   
  274.         }   
  275.     }   
  276.   
  277.     /**  
  278.      * 獲得一個表的主鍵信息  
  279.      */  
  280.     public void getAllPrimaryKeys(String schemaName, String tableName)   
  281.     {   
  282.         try  
  283.         {   
  284.             ResultSet rs = dbMetaData.getPrimaryKeys(null, schemaName, tableName);   
  285.             while (rs.next())   
  286.             {   
  287.                 // column name   
  288.                 String columnName = rs.getString("COLUMN_NAME");   
  289.                 // sequence number within primary key( a value of 1 represents   
  290.                 // the first column of the primary key, a value of 2 would   
  291.                 // represent the second column within the primary key).   
  292.                 short keySeq = rs.getShort("KEY_SEQ");   
  293.                 // primary key name (may be null)   
  294.                 String pkName = rs.getString("PK_NAME");   
  295.                 System.out.println(columnName + "-" + keySeq + "-" + pkName);   
  296.             }   
  297.         } catch (SQLException e)   
  298.         {   
  299.             // TODO: handle SQLException   
  300.             e.printStackTrace();   
  301.         }   
  302.     }   
  303.   
  304.     /**  
  305.      * 獲得一個表的外鍵信息  
  306.      */  
  307.     public void getAllExportedKeys(String schemaName, String tableName)   
  308.     {   
  309.         try  
  310.         {   
  311.             ResultSet rs = dbMetaData.getExportedKeys(null, schemaName, tableName);   
  312.             while (rs.next())   
  313.             {   
  314.                 // primary key table catalog (may be null)   
  315.                 String pkTableCat = rs.getString("PKTABLE_CAT");   
  316.                 // primary key table schema (may be null)   
  317.                 String pkTableSchem = rs.getString("PKTABLE_SCHEM");   
  318.                 // primary key table name   
  319.                 String pkTableName = rs.getString("PKTABLE_NAME");   
  320.                 // primary key column name   
  321.                 String pkColumnName = rs.getString("PKCOLUMN_NAME");   
  322.                 // foreign key table catalog (may be null) being exported (may   
  323.                 // be null)   
  324.                 String fkTableCat = rs.getString("FKTABLE_CAT");   
  325.                 // foreign key table schema (may be null) being exported (may be   
  326.                 // null)   
  327.                 String fkTableSchem = rs.getString("FKTABLE_SCHEM");   
  328.                 // foreign key table name being exported   
  329.                 String fkTableName = rs.getString("FKTABLE_NAME");   
  330.                 // foreign key column name being exported   
  331.                 String fkColumnName = rs.getString("FKCOLUMN_NAME");   
  332.                 // sequence number within foreign key( a value of 1 represents   
  333.                 // the first column of the foreign key, a value of 2 would   
  334.                 // represent the second column within the foreign key).   
  335.                 short keySeq = rs.getShort("KEY_SEQ");   
  336.                 // What happens to foreign key when primary is updated:   
  337.                 // importedNoAction - do not allow update of primary key if it   
  338.                 // has been imported   
  339.                 // importedKeyCascade - change imported key to agree with   
  340.                 // primary key update   
  341.                 // importedKeySetNull - change imported key to NULL if its   
  342.                 // primary key has been updated   
  343.                 // importedKeySetDefault - change imported key to default values   
  344.                 // if its primary key has been updated   
  345.                 // importedKeyRestrict - same as importedKeyNoAction (for ODBC   
  346.                 // 2.x compatibility)   
  347.                 short updateRule = rs.getShort("UPDATE_RULE");   
  348.   
  349.                 // What happens to the foreign key when primary is deleted.   
  350.                 // importedKeyNoAction - do not allow delete of primary key if   
  351.                 // it has been imported   
  352.                 // importedKeyCascade - delete rows that import a deleted key   
  353.                 // importedKeySetNull - change imported key to NULL if its   
  354.                 // primary key has been deleted   
  355.                 // importedKeyRestrict - same as importedKeyNoAction (for ODBC   
  356.                 // 2.x compatibility)   
  357.                 // importedKeySetDefault - change imported key to default if its   
  358.                 // primary key has been deleted   
  359.                 short delRule = rs.getShort("DELETE_RULE");   
  360.                 // foreign key name (may be null)   
  361.                 String fkName = rs.getString("FK_NAME");   
  362.                 // primary key name (may be null)   
  363.                 String pkName = rs.getString("PK_NAME");   
  364.                 // can the evaluation of foreign key constraints be deferred   
  365.                 // until commit   
  366.                 // importedKeyInitiallyDeferred - see SQL92 for definition   
  367.                 // importedKeyInitiallyImmediate - see SQL92 for definition   
  368.                 // importedKeyNotDeferrable - see SQL92 for definition   
  369.                 short deferRability = rs.getShort("DEFERRABILITY");   
  370.                 System.out.println(pkTableCat + "-" + pkTableSchem + "-" + pkTableName + "-" + pkColumnName + "-"  
  371.                         + fkTableCat + "-" + fkTableSchem + "-" + fkTableName + "-" + fkColumnName + "-" + keySeq + "-"  
  372.                         + updateRule + "-" + delRule + "-" + fkName + "-" + pkName + "-" + deferRability);   
  373.             }   
  374.         } catch (SQLException e)   
  375.         {   
  376.             // TODO: handle SQLException   
  377.             e.printStackTrace();   
  378.         }   
  379.     }   
  380.   
  381.     public DatabaseMetaDateApplication()   
  382.     {   
  383.         this.getDatabaseMetaData();   
  384.     }   
  385. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章