Java中DatabaseMetaData 元數據信息


獲取數據庫的相關信息:

1.獲得數據庫的一些相關信息

2.獲得該用戶下面的所有表

3.獲得該用戶下面的所有視圖

4.獲得數據庫中所有方案名稱  

5.獲得表或視圖中的所有列信息

6. 獲得一個表的索引信息

7.獲得一個表的主鍵信息

8.獲得一個表的外鍵信息


[java]  view plain copy print ?
  1. package com.zsw.test;  
  2.   
  3.   
  4. import java.sql.Connection;  
  5. import java.sql.DatabaseMetaData;  
  6. import java.sql.DriverManager;  
  7. import java.sql.ResultSet;  
  8. import java.sql.SQLException;  
  9.   
  10.   
  11. public class DatabaseMetaDateApplication {  
  12.   
  13.   
  14.     private DatabaseMetaData dbMetaData = null;  
  15.     private Connection con = null;  
  16.   
  17.   
  18.     public DatabaseMetaDateApplication() {  
  19.         this.getDatabaseMetaData();  
  20.     }  
  21.   
  22.   
  23.     private void getDatabaseMetaData() {  
  24.         try {  
  25.             if (dbMetaData == null) {  
  26.                 Class.forName("com.mysql.jdbc.Driver");  
  27.                 String url = "jdbc:mysql://localhost:3306/creation_cms";  
  28.                 String user = "root";  
  29.                 String password = "root";  
  30.                 con = DriverManager.getConnection(url, user, password);  
  31.                 dbMetaData = con.getMetaData();  
  32.             }  
  33.         } catch (ClassNotFoundException e) {  
  34.             e.printStackTrace();  
  35.         } catch (SQLException e) {  
  36.             e.printStackTrace();  
  37.         }  
  38.     }  
  39.   
  40.   
  41.     /** 
  42.      * 獲得數據庫的一些相關信息 
  43.      */  
  44.     public void getDataBaseInformations() {  
  45.         try {             
  46.             System.out.println("數據庫已知的用戶: "+ dbMetaData.getUserName());    
  47.             System.out.println("數據庫的系統函數的逗號分隔列表: "+ dbMetaData.getSystemFunctions());    
  48.             System.out.println("數據庫的時間和日期函數的逗號分隔列表: "+ dbMetaData.getTimeDateFunctions());    
  49.             System.out.println("數據庫的字符串函數的逗號分隔列表: "+ dbMetaData.getStringFunctions());    
  50.             System.out.println("數據庫供應商用於 'schema' 的首選術語: "+ dbMetaData.getSchemaTerm());    
  51.             System.out.println("數據庫URL: " + dbMetaData.getURL());    
  52.             System.out.println("是否允許只讀:" + dbMetaData.isReadOnly());    
  53.             System.out.println("數據庫的產品名稱:" + dbMetaData.getDatabaseProductName());    
  54.             System.out.println("數據庫的版本:" + dbMetaData.getDatabaseProductVersion());    
  55.             System.out.println("驅動程序的名稱:" + dbMetaData.getDriverName());    
  56.             System.out.println("驅動程序的版本:" + dbMetaData.getDriverVersion());   
  57.   
  58.   
  59.             System.out.println();    
  60.             System.out.println("數據庫中使用的表類型");    
  61.             ResultSet rs = dbMetaData.getTableTypes();    
  62.             while (rs.next()) {    
  63.                 System.out.println(rs.getString(1));    
  64.             }    
  65.             rs.close();                
  66.             System.out.println();  
  67.         } catch (SQLException e) {  
  68.             e.printStackTrace();  
  69.         }  
  70.     }  
  71.   
  72.   
  73.     /** 
  74.      * 獲得該用戶下面的所有表 
  75.      */  
  76.     public void getAllTableList(String schemaName) {  
  77.         try {  
  78.             // table type. Typical types are "TABLE", "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM".  
  79.             String[] types = { "TABLE" };  
  80.             ResultSet rs = dbMetaData.getTables(null, schemaName, "%", types);  
  81.             while (rs.next()) {  
  82.                 String tableName = rs.getString("TABLE_NAME");  //表名  
  83.                 String tableType = rs.getString("TABLE_TYPE");  //表類型  
  84.                 String remarks = rs.getString("REMARKS");       //表備注  
  85.                 System.out.println(tableName + "-" + tableType + "-" + remarks);  
  86.             }  
  87.         } catch (SQLException e) {  
  88.             e.printStackTrace();  
  89.         }  
  90.     }  
  91.   
  92.   
  93.     /** 
  94.      * 獲得該用戶下面的所有視圖 
  95.      */  
  96.     public void getAllViewList(String schemaName) {  
  97.          try{    
  98.              String[] types = { "VIEW" };                 
  99.              ResultSet rs = dbMetaData.getTables(null, schemaName, "%", types);  
  100.              while (rs.next()){  
  101.                  String viewName = rs.getString("TABLE_NAME"); //視圖名  
  102.                  String viewType = rs.getString("TABLE_TYPE"); //視圖類型  
  103.                  String remarks = rs.getString("REMARKS");      //視圖備注  
  104.                  System.out.println(viewName + "-" + viewType + "-" + remarks);  
  105.              }  
  106.          } catch (SQLException e) {  
  107.              e.printStackTrace();  
  108.          }  
  109.     }  
  110.       
  111.      /**   
  112.      * 獲得數據庫中所有方案名稱   
  113.      */    
  114.     public void getAllSchemas(){  
  115.         try{  
  116.             ResultSet rs = dbMetaData.getSchemas();   
  117.             while (rs.next()){     
  118.                 String tableSchem = rs.getString("TABLE_SCHEM");     
  119.                 System.out.println(tableSchem);     
  120.             }     
  121.         } catch (SQLException e){  
  122.             e.printStackTrace();     
  123.         }     
  124.     }     
  125.   
  126.   
  127.     /** 
  128.      * 獲得表或視圖中的所有列信息 
  129.      */  
  130.     public void getTableColumns(String schemaName, String tableName) {  
  131.            
  132.         try{     
  133.                   
  134.             ResultSet rs = dbMetaData.getColumns(null, schemaName, tableName, "%");              
  135.             while (rs.next()){  
  136.                     String tableCat = rs.getString("TABLE_CAT");//表目錄(可能為空)                  
  137.                     String tableSchemaName = rs.getString("TABLE_SCHEM");//表的架構(可能為空)     
  138.                     String tableName_ = rs.getString("TABLE_NAME");//表名  
  139.                     String columnName = rs.getString("COLUMN_NAME");//列名  
  140.                     int dataType = rs.getInt("DATA_TYPE"); //對應的java.sql.Types類型     
  141.                     String dataTypeName = rs.getString("TYPE_NAME");//java.sql.Types類型   名稱  
  142.                     int columnSize = rs.getInt("COLUMN_SIZE");//列大小  
  143.                     int decimalDigits = rs.getInt("DECIMAL_DIGITS");//小數位數  
  144.                     int numPrecRadix = rs.getInt("NUM_PREC_RADIX");//基數(通常是10或2)  
  145.                     int nullAble = rs.getInt("NULLABLE");//是否允許為null  
  146.                     String remarks = rs.getString("REMARKS");//列描述  
  147.                     String columnDef = rs.getString("COLUMN_DEF");//默認值  
  148.                     int sqlDataType = rs.getInt("SQL_DATA_TYPE");//sql數據類型  
  149.                     int sqlDatetimeSub = rs.getInt("SQL_DATETIME_SUB");   //SQL日期時間分?  
  150.                     int charOctetLength = rs.getInt("CHAR_OCTET_LENGTH");   //char類型的列中的最大字節數  
  151.                     int ordinalPosition = rs.getInt("ORDINAL_POSITION");  //表中列的索引(從1開始)  
  152.                       
  153.                     /** 
  154.                      * ISO規則用來確定某一列的為空性。 
  155.                      * 是---如果該參數可以包括空值; 
  156.                      * 無---如果參數不能包含空值 
  157.                      * 空字符串---如果參數為空性是未知的 
  158.                      */  
  159.                     String isNullAble = rs.getString("IS_NULLABLE");  
  160.                       
  161.                     /** 
  162.                      * 指示此列是否是自動遞增 
  163.                      * 是---如果該列是自動遞增 
  164.                      * 無---如果不是自動遞增列 
  165.                      * 空字串---如果不能確定它是否 
  166.                      * 列是自動遞增的參數是未知 
  167.                      */  
  168.                     String isAutoincrement = rs.getString("IS_AUTOINCREMENT");     
  169.                       
  170.                     System.out.println(tableCat + "-" + tableSchemaName + "-" + tableName_ + "-" + columnName + "-"    
  171.                             + dataType + "-" + dataTypeName + "-" + columnSize + "-" + decimalDigits + "-" + numPrecRadix     
  172.                             + "-" + nullAble + "-" + remarks + "-" + columnDef + "-" + sqlDataType + "-" + sqlDatetimeSub     
  173.                             + charOctetLength + "-" + ordinalPosition + "-" + isNullAble + "-" + isAutoincrement + "-");     
  174.                 }     
  175.             } catch (SQLException e){  
  176.                 e.printStackTrace();     
  177.             }  
  178.     }  
  179.   
  180.   
  181.     /** 
  182.      * 獲得一個表的索引信息 
  183.      */  
  184.     public void getIndexInfo(String schemaName, String tableName) {  
  185.         try{  
  186.             ResultSet rs = dbMetaData.getIndexInfo(null, schemaName, tableName, truetrue);  
  187.             while (rs.next()){  
  188.                 boolean nonUnique = rs.getBoolean("NON_UNIQUE");//非唯一索引(Can index values be non-unique. false when TYPE is  tableIndexStatistic   )  
  189.                 String indexQualifier = rs.getString("INDEX_QUALIFIER");//索引目錄(可能為空)  
  190.                 String indexName = rs.getString("INDEX_NAME");//索引的名稱  
  191.                 short type = rs.getShort("TYPE");//索引類型  
  192.                 short ordinalPosition = rs.getShort("ORDINAL_POSITION");//在索引列順序號  
  193.                 String columnName = rs.getString("COLUMN_NAME");//列名  
  194.                 String ascOrDesc = rs.getString("ASC_OR_DESC");//列排序順序:升序還是降序  
  195.                 int cardinality = rs.getInt("CARDINALITY");   //基數  
  196.                 System.out.println(nonUnique + "-" + indexQualifier + "-" + indexName + "-" + type + "-" + ordinalPosition + "-" + columnName + "-" + ascOrDesc + "-" + cardinality);     
  197.             }     
  198.         } catch (SQLException e){  
  199.             e.printStackTrace();     
  200.         }   
  201.     }  
  202.   
  203.   
  204.     /** 
  205.      * 獲得一個表的主鍵信息 
  206.      */  
  207.     public void getAllPrimaryKeys(String schemaName, String tableName) {  
  208.         try{  
  209.             ResultSet rs = dbMetaData.getPrimaryKeys(null, schemaName, tableName);  
  210.             while (rs.next()){  
  211.                 String columnName = rs.getString("COLUMN_NAME");//列名  
  212.                 short keySeq = rs.getShort("KEY_SEQ");//序列號(主鍵內值1表示第一列的主鍵,值2代表主鍵內的第二列)  
  213.                 String pkName = rs.getString("PK_NAME"); //主鍵名稱    
  214.                 System.out.println(columnName + "-" + keySeq + "-" + pkName);     
  215.             }  
  216.         }catch (SQLException e){  
  217.             e.printStackTrace();  
  218.         }  
  219.     }  
  220.   
  221.   
  222.     /** 
  223.      * 獲得一個表的外鍵信息 
  224.      */  
  225.     public void getAllExportedKeys(String schemaName, String tableName) {  
  226.           
  227.         try{  
  228.             ResultSet rs = dbMetaData.getExportedKeys(null, schemaName, tableName);  
  229.             while (rs.next()){  
  230.                 String pkTableCat = rs.getString("PKTABLE_CAT");//主鍵表的目錄(可能為空)  
  231.                 String pkTableSchem = rs.getString("PKTABLE_SCHEM");//主鍵表的架構(可能為空)  
  232.                 String pkTableName = rs.getString("PKTABLE_NAME");//主鍵表名   
  233.                 String pkColumnName = rs.getString("PKCOLUMN_NAME");//主鍵列名    
  234.                 String fkTableCat = rs.getString("FKTABLE_CAT");//外鍵的表的目錄(可能為空)出口(可能為null)  
  235.                 String fkTableSchem = rs.getString("FKTABLE_SCHEM");//外鍵表的架構(可能為空)出口(可能為空)  
  236.                 String fkTableName = rs.getString("FKTABLE_NAME");//外鍵表名  
  237.                 String fkColumnName = rs.getString("FKCOLUMN_NAME"); //外鍵列名                  
  238.                 short keySeq = rs.getShort("KEY_SEQ");//序列號(外鍵內值1表示第一列的外鍵,值2代表在第二列的外鍵)。  
  239.                   
  240.                 /** 
  241.                  * hat happens to foreign key when primary is updated:  
  242.                  * importedNoAction - do not allow update of primary key if it has been imported 
  243.                  * importedKeyCascade - change imported key to agree with primary key update  
  244.                  * importedKeySetNull - change imported key to NULL if its primary key has been updated 
  245.                  * importedKeySetDefault - change imported key to default values if its primary key has been updated 
  246.                  * importedKeyRestrict - same as importedKeyNoAction (for ODBC 2.x compatibility)    
  247.                  */  
  248.                 short updateRule = rs.getShort("UPDATE_RULE");  
  249.                   
  250.                 /** 
  251.                  * What happens to the foreign key when primary is deleted. 
  252.                  * importedKeyNoAction - do not allow delete of primary key if it has been imported 
  253.                  * importedKeyCascade - delete rows that import a deleted key  
  254.                  * importedKeySetNull - change imported key to NULL if its primary key has been deleted  
  255.                  * importedKeyRestrict - same as importedKeyNoAction (for ODBC 2.x compatibility) 
  256.                  * importedKeySetDefault - change imported key to default if its primary key has been deleted    
  257.                  */  
  258.                 short delRule = rs.getShort("DELETE_RULE");  
  259.                 String fkName = rs.getString("FK_NAME");//外鍵的名稱(可能為空)  
  260.                 String pkName = rs.getString("PK_NAME");//主鍵的名稱(可能為空)  
  261.                   
  262.                 /** 
  263.                  * can the evaluation of foreign key constraints be deferred until commit 
  264.                  * importedKeyInitiallyDeferred - see SQL92 for definition 
  265.                  * importedKeyInitiallyImmediate - see SQL92 for definition  
  266.                  * importedKeyNotDeferrable - see SQL92 for definition    
  267.                  */  
  268.                 short deferRability = rs.getShort("DEFERRABILITY");  
  269.                   
  270.                 System.out.println(pkTableCat + "-" + pkTableSchem + "-" + pkTableName + "-" + pkColumnName + "-"    
  271.                         + fkTableCat + "-" + fkTableSchem + "-" + fkTableName + "-" + fkColumnName + "-" + keySeq + "-"    
  272.                         + updateRule + "-" + delRule + "-" + fkName + "-" + pkName + "-" + deferRability);     
  273.             }  
  274.         } catch (SQLException e){  
  275.             e.printStackTrace();     
  276.         }  
  277.     }  
  278.   
  279.   
  280.     public void colseCon() {  
  281.         try {  
  282.             if (con != null) {  
  283.                 con.close();  
  284.             }  
  285.         } catch (SQLException e) {  
  286.             e.printStackTrace();  
  287.         }  
  288.     }  
  289.   
  290.   
  291.     public static void main(String[] args) {  
  292.         DatabaseMetaDateApplication metaData = new DatabaseMetaDateApplication();  
  293. //      metaData.getDataBaseInformations();  
  294. //      metaData.getAllTableList(null);  
  295. //      metaData.getAllViewList(null);  
  296. //      metaData.getAllSchemas();  
  297. //      metaData.getTableColumns(null, "zsc_admin");  
  298. //      metaData.getIndexInfo(null, "zsc_admin");  
  299. //      metaData.getAllPrimaryKeys(null, "zsc_admin");  
  300.         metaData.getAllExportedKeys(null"zsc_admin");  
  301.           
  302.           
  303.     }  
  304.   
  305.   
  306. }  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM