DatabaseMetaData类

article/2025/11/11 9:23:19

 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

 

转载于:https://www.cnblogs.com/dnn179/p/DatabaseMetaData.html


http://chatgpt.dhexx.cn/article/T9Tqt5Zk.shtml

相关文章

数据库之-元数据 DatabaseMetaData 初学

DatabaseMetaData和ResultSetMetaData就是两个常用的获取数据库元数据相关信息的接口&#xff0c;本文讲解DatabaseMetaData和ResultSetMetaData接口获取元数据的方法。 获取数据库的所有表&#xff1a;(以MySQL和Oracle为例&#xff0c;其他类型的数据库接触不过&#xff0c;…

php备忘录模式

CleverCode最近在看备忘录模式。 1 模式介绍 在不破坏封闭的前提下&#xff0c;捕获一个对象的内部状态&#xff0c;并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。 2 模式中的角色 1.Originator(发起人)&#xff1a;负责创建一个备忘录Memento&…

设计模式 — 行为型模式 — 备忘录模式

目录 文章目录 目录备忘录模式应用场景代码示例 备忘录模式 备忘录模式&#xff0c;在不破坏封闭的前提下&#xff0c;捕获一个对象的内部状态&#xff0c;并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。 简单来说&#xff0c;就是在运行过程中我们…

“备忘录模式”就这么简单

备忘录模式的官方定义&#xff1a; 在不破坏封装性的前提下&#xff0c;获取一个对象的内部状态&#xff0c;并在该对象之外保存这些状态。这样以后就可以通过该对象恢复到原先保存的状态。 大白话说&#xff1a; 一个对象中一般都封装了很多属性&#xff0c;这些属性的值会随…

(18)备忘录模式

&#xfeff;&#xfeff; &#xff08;18&#xff09;备忘录模式 定义&#xff1a;在不破坏封装性的前提下&#xff0c;捕获一个对象的内部状态&#xff0c;并在该对象之外保存这个状态。这样就可以将该对象恢复到原先保存的状态 类型&#xff1a;行为类 类图&#xff1a; 我们…

Java设计模式-备忘录模式、备忘录模式应用场景是什么、又怎么使用

继续整理记录这段时间来的收获&#xff0c;详细代码可在我的Gitee仓库Java设计模式克隆下载学习使用&#xff01; 6.11 备忘录模式 6.11.1 定义 又称快照模式&#xff0c;在不破坏封装性的前提下&#xff0c;捕获一个对象的内部状态&#xff0c;并在该对象之外保存此状态&am…

C++设计模式(17)——备忘录模式

亦称&#xff1a; 快照、Snapshot、Memento 意图 备忘录模式是一种行为设计模式&#xff0c; 允许在不暴露对象实现细节的情况下保存和恢复对象之前的状态。 问题 假如你正在开发一款文字编辑器应用程序。 除了简单的文字编辑功能外&#xff0c; 编辑器中还要有设置文本格…

Java备忘录模式(Memento)

本文我们来介绍下java23种设计模式中的备忘录模式。 备忘录模式Memento 使用场景 录入大批人员资料。正在录入当前人资料时&#xff0c;发现上一个人录错了&#xff0c; 此时需要恢复上一个人的资料&#xff0c;再进行修改。Word文档编辑时&#xff0c;忽然电脑死机或断电&a…

Java设计模式之备忘录模式

Java设计模式之备忘录模式 1. 备忘录模式概述1.1 备忘录模式简介1.2 备忘录模式类图1.3 备忘录模式的注意事项和细节 2. 备忘录模式实现2.1 项目说明2.2 项目实现 1. 备忘录模式概述 1.1 备忘录模式简介 1.备忘录模式(Memento Pattern)在不破坏封装性的前提下,捕获一个对象的…

【设计模式】备忘录模式

设计模式总结链接 备忘录模式又叫做快照模式(Snapshot Pattern)或Token模式&#xff0c;是对象的行为模式。   备忘录对象是一个用来存储另外一个对象内部状态的快照的对象。备忘录模式的用意是在不破坏封装的条件下&#xff0c;将一个对象的状态捕捉(Capture)住&#xff…

23种设计模式——备忘录模式

目录 备忘录模式&#xff08;Memento&#xff09; UML图 示例代码 适用场景 优缺点 备忘录模式和原型模式 例子——游戏进度存档 例子——象棋中的悔棋 备忘录模式&#xff08;Memento&#xff09; 本质&#xff1a;保存和恢复内部状态 备忘录模式&#xff1a;在不破坏…

23种设计模式之---备忘录模式

前言 网上搜索备忘录设计模式&#xff0c;基本上均是在一个GoF&#xff0c;基础上衍生下来的。为了避免重复造轮子&#xff0c;这里会结合网上demo&#xff0c;和自己理解进行总结 定义&#xff1a;备忘录&#xff08;Memento&#xff09;模式又称标记&#xff08;Token&…

备忘录模式介绍

备忘录模式介绍 一、基本介绍二、代码实现三、UML类图四、备忘录模式小结其他设计模式 一、基本介绍 备忘录模式&#xff08;Memento Pattern&#xff09;属于行为型模式&#xff0c;是指在不破坏封装性的前提下&#xff0c;捕获一个对象的内部状态&#xff0c;并在该对象之外…

设计模式 | 备忘录模式及典型应用

本文的主要内容&#xff1a; 介绍备忘录模式示例备忘录模式总结 备忘录模式 备忘录模式经常可以遇到&#xff0c;譬如下面这些场景&#xff1a; 浏览器回退&#xff1a;浏览器一般有浏览记录&#xff0c;当我们在一个网页上点击几次链接之后&#xff0c;可在左上角点击左箭头…

设计模式之备忘录模式

一、备忘录模式 备忘录模式&#xff08;Memento Pattern&#xff09;保存一个对象的某个状态&#xff0c;以便在适当的时候恢复对象。备忘录模式属于行为型模式。 原发器(Originator)角色&#xff1a;原发器根据需要决定将自己的哪些内部状态保存到备忘录中&#xff0c;并可以使…

备忘录模式(Java)

备忘录模式&#xff08;Java&#xff09; 下面是关于我所写的所有设计模式代码&#xff08;还是建议自己手打或者想一个别的例子练习一次&#xff09; (https://github.com/lihang212010/DesignPatterns-/tree/master/designpatterns/src) 先来张百度的UML 下面是我例子的U…

撤销功能的实现——备忘录模式(二)

21.2 备忘录模式概述 备忘录模式提供了一种状态恢复的实现机制&#xff0c;使得用户可以方便地回到一个特定的历史步骤&#xff0c;当新的状态无效或者存在问题时&#xff0c;可以使用暂时存储起来的备忘录将状态复原&#xff0c;当前很多软件都提供了撤销(Undo)操作&#xff0…

18-备忘录模式

文章目录 游戏角色状态恢复问题备忘录模式基本介绍备忘录模式解决游戏角色状态回复问题备忘录模式的注意事项和细节 游戏角色状态恢复问题 游戏鱼色有攻击力和防御力&#xff0c;在大战 Boss 前保存自身的状态&#xff08;攻击力和防御力&#xff09;&#xff0c;当大战 Boss …

详解设计模式:备忘录模式

详解设计模式&#xff1a;备忘录模式 备忘录模式&#xff08;Memento Pattern&#xff09;也被称为快照模式&#xff08;Snapshot Pattern&#xff09;、Token 模式&#xff08;Token Pattern&#xff09;&#xff0c;是在 GoF 23 种设计模式中定义了的行为型模式。 备忘录模式…

JAVA设计模式--备忘录模式

目录 一、什么是备忘录模式 二、备忘录模式的结构 三、备忘录模式的适用性 四、备忘录模式的实现 五、备忘录模式的优缺点 六、总结 一、什么是备忘录模式 备忘录(Memento)模式又叫作快照(Snapshot)模式或Token模式&#xff0c;是一种对象的行为模式。在备忘录模式里&am…