DatabaseMetaData類


 DatabaseMetaData類是java.sql包中的類,利用它可以獲取我們連接到的數據庫的結構、存儲等很多信息。如:

         1、數據庫與用戶,數據庫標識符以及函數與存儲過程。
         2、數據庫限制。
         3、數據庫支持不支持的功能。
         4、架構、編目、表、列和視圖等。

        通過調用DatabaseMetaData的各種方法,程序可以動態的了解一個數據庫。由於這個類中的方法非常的多那么就介紹幾個常用的方法來給大家參考。

    (1) DatabaseMetaData實例的獲取

        Connection conn = DriverManager.getConnection(……);
        DatabaseMetaData dbmd = Conn.getMetaData();

        創建了這個實例,就可以使用它的方法來獲取數據庫得信息。主要使用如下的方法:

   (2) 獲得當前數據庫以及驅動的信息

        dbmd.getDatabaseProductName():用以獲得當前數據庫是什么數據庫。比如oracle,access等。返回的是字符串。
        dbmd.getDatabaseProductVersion():獲得數據庫的版本。返回的字符串。
        dbmd.getDriverVersion():獲得驅動程序的版本。返回字符串。
        dbmd.getTypeInfo() :獲得當前數據庫的類型信息

   (3)  獲得當前數據庫中表的信息

        dbmd.getTables(String catalog,String schema,String tableName,String[] types),

        這個方法帶有四個參數,它們表示的含義如下:
        String catalog:要獲得表所在的編目。"“”"意味着沒有任何編目,Null表示所有編目。

        String schema:要獲得表所在的模式。"“”"意味着沒有任何模式,Null表示所有模式。

        String tableName:指出要返回表名與該參數匹配的那些表,

        String types:一個指出返回何種表的數組。

        可能的數組項是:"TABLE"、"VIEW"、"SYSTEM TABLE", "GLOBAL TEMPORARY","LOCAL  TEMPORARY","ALIAS","SYSNONYM"。

        通過getTables()方法返回的結果集中的每個表都有下面是10字段的描述信息,而且只有10個。通常我們用到的也就是標紅的幾個字段。而且在結果集中直接使用下面字段前面的序號即可獲取字段值。

        1.TABLE_CAT        (String)   => 表所在的編目(可能為空)  

        2.TABLE_SCHEM (String)   => 表所在的模式(可能為空) 

        3.TABLE_NAME    (String)   => 表的名稱

        4.TABLE_TYPE     (String)    => 表的類型。

                典型的有 "TABLE", "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY", "LOCAL  TEMPORARY", "ALIAS", "SYNONYM". 

        5.REMARKS          (String)       => 解釋性的備注

        6.TYPE_CAT          (String)      =>編目類型(may be null) 

        7.TYPE_SCHEM   (String)      => 模式類型(may be null) 

        8.TYPE_NAME      (String)      => 類型名稱(may be null) 

        9.SELF_REFERENCING_COL_NAME    (String) => name of the designated "identifier" column of a typed table (may be null) 

       10.REF_GENERATION   (String)    => specifies how values in SELF_REFERENCING_COL_NAME are created.

                   它的值有:"SYSTEM"、"USER"、"DERIVED",也可能為空。

  (4)獲得某個表的列信息

        dbmd.getColumns(String catalog,String schama,String tablename,String columnPattern,

        通過getColumns()方法返回的結果集中的每一列都有下面是23個字段段的描述信息,而且只有23個。通常我們用到的也就是標紅的字段。而且在結果集中直接使用下面字段前面的序號即可獲取字段值。

        1.TABLE_CAT String => table catalog (may be null)

        2.TABLE_SCHEM String => table schema (may be null)

        3.TABLE_NAME String => table name (表名稱)

        4.COLUMN_NAME String => column name(列名)

        5.DATA_TYPE int => SQL type from java.sql.Types(列的數據類型)

        6.TYPE_NAME String => Data source dependent type name, for a UDT the type name is fully qualified

        7.COLUMN_SIZE int => column size.

        8.BUFFER_LENGTH is not used.

        9.DECIMAL_DIGITS int => the number of fractional digits. Null is returned for data types where DECIMAL_DIGITS is not applicable.

       10.NUM_PREC_RADIX int => Radix (typically either 10 or 2)

       11.NULLABLE int => is NULL allowed.

       12.REMARKS String => comment describing column (may be null)

       13.COLUMN_DEF String => default value for the column, (may be null)

       14.SQL_DATA_TYPE int => unused

       15.SQL_DATETIME_SUB int => unused

       16.CHAR_OCTET_LENGTH int => for char types the maximum number of bytes in the column

       17.ORDINAL_POSITION int => index of column in table (starting at 1)

       18.IS_NULLABLE String => ISO rules are used to determine the nullability for a column.

       19.SCOPE_CATLOG String => catalog of table that is the scope of a reference attribute (null if DATA_TYPE isn't REF)

        20.SCOPE_SCHEMA String => schema of table that is the scope of a reference attribute (null if the DATA_TYPE isn't REF)

        21.SCOPE_TABLE String => table name that this the scope of a reference attribure (null if the DATA_TYPE isn't REF)

        22.SOURCE_DATA_TYPE short => source type of a distinct type or user-generated Ref type, SQL type from java.sql.Types

       23.IS_AUTOINCREMENT String => Indicates whether this column is auto incremented

  (5)獲得表的關鍵字信息

        dbmd.getPrimaryKeys(String catalog, String schema, String table),

       通過getPrimaryKeys方法返回的結果集中的每一列都有下面是6個字段段的描述信息,而且只有6個。通常我們用到的也就是標紅的字段。而且在結果集中直接使用下面字段前面的序號即可獲取字段值。

       1.TABLE_CAT String => table catalog (may be null)

       2.TABLE_SCHEM String => table schema (may be null)

       3.TABLE_NAME String => table name

       4.COLUMN_NAME String => column name

       5.KEY_SEQ short => sequence number within primary key

       6.PK_NAME String => primary key name (may be null)

        這兩個方法中的參數的含義和上面的介紹的是相同的。凡是pattern的都是可以用通配符匹配的。getColums()返回的是結果集,這個結果集包括了列的所有信息,類型,名稱,可否為空等。getPrimaryKey()則是返回了某個表的關鍵字的結果集。

  (6)獲取指定表的外鍵信息

        dbmd.getExportedKeys(String catalog, String schema, String table) 

        通過getPrimaryKeys方法返回的結果集中的每一列都有下面是11個字段段的描述信息,而且只有11個。通常我們用到的也就是標紅的字段。而且在結果集中直接使用下面字段前面的序號即可獲取字段值。

         1.PKTABLE_CAT String => primary key table catalog (may be null) 

         2.PKTABLE_SCHEM String => primary key table schema (may be null) 

         3.PKTABLE_NAME String => primary key table name 

         4.PKCOLUMN_NAME String => primary key column name 

         5.FKTABLE_CAT String => foreign key table catalog (may be null) being exported (may be null) 

         6.FKTABLE_SCHEM String => foreign key table schema (may be null) being exported (may be null) 

         7.FKTABLE_NAME String => foreign key table name being exported 

         8.FKCOLUMN_NAME String => foreign key column name being exported 

         9.KEY_SEQ short => sequence number within foreign key

        10.UPDATE_RULE short => What happens to foreign key when primary is updated:

        11.DELETE_RULE short => What happens to the foreign key when primary is deleted.

  (7)反向設計表

     通過getTables(),getColumns(),getPrimaryKeys()就可以完成表的反向設計了。主要步驟如下:

      1、通過getTables()獲得數據庫中表的信息。
      2、對於每個表使用,getColumns(),getPrimaryKeys()獲得相應的列名,類型,限制條件,關鍵字等。
      3、通過1,2獲得信息可以生成相應的建表的SQL語句。

      通過上述三步完成反向設計表的過程。

  (8)代碼示例

        下面我做了一個將DataBaseMetaData與Dom4j相結合的例子來實現數據庫中的表轉換成xml文件,代碼已通過測試

首先借助jdk 6.x自帶的的Derby數據庫創建一個名為DerByDB的數據庫

 1 package com.bjsxt.jdbc;
 2 import java.sql.Connection;
 3 import java.sql.DriverManager;
 4 import java.sql.ResultSet;
 5 import java.sql.SQLException;
 6 import java.sql.Statement;
 7 import java.util.Properties;
 8 public class JavaDBTest {
 9     public static void main(String[] args) {
10         try {
11          // load the driver
12             Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
13             System.out.println("Load the driver");
14             Connection conn = null;
15             Properties props = new Properties();
16             props.put("user", "user1");  props.put("password", "user1");
17             //create and connect the database named helloDB 
18             conn=DriverManager.getConnection("jdbc:derby:DerByDB;create=true", props);
19             System.out.println("create and connect to DerByDB");
20             conn.setAutoCommit(false);
21             //創建一個學生表(student),並插入兩條記錄         
22 
23             Statement sm = conn.createStatement();
24             sm.execute("create table student(name varchar(40) primary key, score int)");
25             System.out.println("Created table student");
26             sm.execute("insert into student values('jack', 86)");
27             sm.execute("insert into student values('kice', 92)");
28             //創建一個教師表(teacher),並插入兩條記錄 
29 
30             sm.execute("create table teacher(name varchar(40), age int)");
31             System.out.println("Created table teacher");
32             sm.execute("insert into teacher values('wang li', 47)");
33             sm.execute("insert into teacher values('liu hua', 52)");
34             // list the two records from student
35             ResultSet rs1 = sm.executeQuery("SELECT name, score FROM student ORDER BY score");
36             System.out.println("==============");
37             System.out.println("name\tscore");
38             while(rs1.next()) {
39                 StringBuilder builder = new StringBuilder(rs1.getString(1));
40                 builder.append("\t");
41                 builder.append(rs1.getInt(2));
42                 System.out.println(builder.toString());
43             }
44             rs1.close();
45             // list the two records from teacher
46             ResultSet rs2 = sm.executeQuery("SELECT name, age FROM teacher ORDER BY age");
47             System.out.println("==============");
48             System.out.println("name\tage");
49             while(rs2.next()) {
50                 StringBuilder builder = new StringBuilder(rs2.getString(1));
51                 builder.append("\t");
52                 builder.append(rs2.getInt(2));
53                 System.out.println(builder.toString());
54             }
55             System.out.println("==============");
56             rs2.close();
57             sm.close();
58             System.out.println("Closed resultset and statement");
59             conn.commit();
60             conn.close();
61             System.out.println("Committed transaction and closed connection");
62             
63             try { // perform a clean shutdown 
64                 DriverManager.getConnection("jdbc:derby:;shutdown=true");
65             } catch (SQLException se) {
66                 System.out.println("Database shut down normally");
67             }
68         } catch (Throwable e) {
69             e.printStackTrace();
70         }
71         System.out.println("SimpleApp finished");
72     }
73 }
View Code

 

 

然后利用DataBaseMetaData與Dom4j 實現Derby數據庫中的表轉換成xml文件,代碼如下:

  1 package com.bjsxt.jdbc;
  2 import java.io.File;
  3 import java.io.FileWriter;
  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 import java.sql.Types;
 10 import java.util.Iterator;
 11 import java.util.List;
 12 import java.util.Properties;
 13 import org.dom4j.Attribute;
 14 import org.dom4j.Document;
 15 import org.dom4j.DocumentHelper;
 16 import org.dom4j.Element;
 17 import org.dom4j.Node;
 18 import org.dom4j.io.OutputFormat;
 19 import org.dom4j.io.SAXReader;
 20 import org.dom4j.io.XMLWriter;
 21 public class DatabaseMetaDataTest {
 22  public static void main(String[] args) throws Exception {
 23   Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
 24          System.out.println("Load the driver");
 25          Connection conn = null;
 26          Properties props = new Properties();
 27          props.put("user", "user1");  props.put("password", "user1");
 28          conn=DriverManager.getConnection("jdbc:derby:DerByDB;create=false", props);
 29          System.out.println("connect to DerByDB");
 30          DatabaseMetaData dbmd = conn.getMetaData();
 31          System.out.println("====getTables()方法====");
 32          ResultSet rs1 = dbmd.getTables(null, null, "STUDENT", new String[]{"TABLE"});
 33          while(rs1.next()) {    //其實結果集中只有一項,那就是TEACHER這個表。
 34          String tname=rs1.getString(3); //獲取表名
 35          String ttype=rs1.getString(4);  //獲取表類型
 36          Document document = DocumentHelper.createDocument(); //建立document對象 
 37          Element databaseElement = document.addElement("database");
 38          Element stuElement=databaseElement.addElement(tname);
 39          stuElement.addAttribute("表類型",ttype);
 40          try{
 41                OutputFormat opf=OutputFormat.createPrettyPrint();  //美化格式
 42                //解決中文亂碼問題,在生成的xml文檔聲明中可以看到設置的編碼。
 43                opf.setEncoding("gbk");   
 44                // 將document中的內容寫入文件中
 45                XMLWriter writer = new XMLWriter(new FileWriter(new File("student.xml")),opf); 
 46                writer.write(document);
 47                writer.close();           
 48         }catch(Exception ex){
 49                ex.printStackTrace();
 50         }
 51         }
 52         System.out.println("getTables is over");
 53         System.out.println("====getColumns()方法====");  
 54 
 55         //最后一個null表示取出所有的列
 56         ResultSet rs2 = dbmd.getColumns(null, null, "STUDENT", null); 
 57         while(rs2.next()) {                     
 58              String colName=rs2.getString(4);        //列名稱
 59              int dataType = rs2.getInt("DATA_TYPE"); //數據類型
 60              String dt=null;
 61               if(dataType==Types.VARCHAR) {
 62                       dt="varchar";           
 63               }else if (dataType==Types.INTEGER) {
 64                       dt="int";
 65               }
 66               try {
 67                    SAXReader saxReader = new SAXReader(); 
 68                    Document document = saxReader.read("student.xml");            
 69                    Node node = document.selectSingleNode("//STUDENT");
 70                    Element studentElement = (Element)node;
 71                    studentElement.addElement(colName).setText(dt);
 72                    //美化格式,此時的xml文檔多行書寫
 73                    OutputFormat opf=OutputFormat.createPrettyPrint();
 74                    //解決中文亂碼問題,在生成的xml文檔聲明中可以看到設置的編碼。  
 75                    opf.setEncoding("gbk"); 
 76                    //將document中的內容寫入文件中      
 77                    XMLWriter writer = new XMLWriter(new FileWriter("student.xml"),opf);
 78                    writer.write(document);
 79                    writer.close();              
 80                }catch (Exception e) {
 81                         e.printStackTrace();
 82                }
 83           }
 84          System.out.println("getColumns is over");
 85          System.out.println("====getPrimaryKeys()方法====");
 86          ResultSet rs3 =dbmd.getPrimaryKeys(null, null, "STUDENT");
 87          while(rs3.next()) {
 88          String  pname=rs3.getString(4);     //列名稱 
 89          System.out.println(pname);
 90           try {
 91                  SAXReader saxReader = new SAXReader(); 
 92                  Document document = saxReader.read("student.xml");
 93                  List<Node> list = document.selectNodes("//STUDENT");
 94                  Iterator<Node> iter=list.iterator();
 95                  while(iter.hasNext()){
 96                       Element studentElement = (Element)iter.next();
 97                       studentElement.addAttribute("primary", pname);
 98                  }                 
 99 //              Node node = document.selectSingleNode("//STUDENT");
100 //              Element studentElement = (Element)node;
101 //              studentElement.addAttribute("primary", pname);               
102 //              Node node = document.selectSingleNode("//STUDENT/@表類型");
103 //              Attribute stype = (Attribute)node;
104 //              stype.setValue("table");
105 //              Element studentElement = (Element)node;
106                 //美化格式,此時的xml文檔多行書寫
107                 OutputFormat opf=OutputFormat.createPrettyPrint();  
108                 //解決中文亂碼問題,在生成的xml文檔聲明中可以看到設置的編碼。  
109                 opf.setEncoding("gbk");      
110                 //將document中的內容寫入文件中 
111                 XMLWriter writer = new XMLWriter(new FileWriter("student.xml"),opf); 
112                 writer.write(document);
113                 writer.close();
114             }catch (Exception e) {
115                 e.printStackTrace();
116             }          
117          }
118          rs1.close();
119          rs2.close();
120          rs3.close();
121          conn.close();
122          try { 
123              DriverManager.getConnection("jdbc:derby:;shutdown=true");
124          } catch (SQLException se) {
125                   System.out.println("Database shut down normally");
126          }
127      }
128 }
View Code

 


免責聲明!

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



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