DatabaseMetaData类的使用

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的数据库

package com.bjsxt.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JavaDBTest {
    public static void main(String[] args) {
        try {
         // load the driver
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
            System.out.println("Load the driver");
            Connection conn = null;
            Properties props = new Properties();
            props.put("user", "user1");  props.put("password", "user1");
            //create and connect the database named helloDB
            conn=DriverManager.getConnection("jdbc:derby:DerByDB;create=true", props);
            System.out.println("create and connect to DerByDB");
            conn.setAutoCommit(false);
            //创建一个学生表(student),并插入两条记录         

            Statement sm = conn.createStatement();
            sm.execute("create table student(name varchar(40) primary key, score int)");
            System.out.println("Created table student");
            sm.execute("insert into student values('jack', 86)");
            sm.execute("insert into student values('kice', 92)");
            //创建一个教师表(teacher),并插入两条记录 

            sm.execute("create table teacher(name varchar(40), age int)");
            System.out.println("Created table teacher");
            sm.execute("insert into teacher values('wang li', 47)");
            sm.execute("insert into teacher values('liu hua', 52)");
            // list the two records from student
            ResultSet rs1 = sm.executeQuery("SELECT name, score FROM student ORDER BY score");
            System.out.println("==============");
            System.out.println("name\tscore");
            while(rs1.next()) {
                StringBuilder builder = new StringBuilder(rs1.getString(1));
                builder.append("\t");
                builder.append(rs1.getInt(2));
                System.out.println(builder.toString());
            }
            rs1.close();
            // list the two records from teacher
            ResultSet rs2 = sm.executeQuery("SELECT name, age FROM teacher ORDER BY age");
            System.out.println("==============");
            System.out.println("name\tage");
            while(rs2.next()) {
                StringBuilder builder = new StringBuilder(rs2.getString(1));
                builder.append("\t");
                builder.append(rs2.getInt(2));
                System.out.println(builder.toString());
            }
            System.out.println("==============");
            rs2.close();
            sm.close();
            System.out.println("Closed resultset and statement");
            conn.commit();
            conn.close();
            System.out.println("Committed transaction and closed connection");
           
            try { // perform a clean shutdown
                DriverManager.getConnection("jdbc:derby:;shutdown=true");
            } catch (SQLException se) {
                System.out.println("Database shut down normally");
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        System.out.println("SimpleApp finished");
    }
}

然后利用DataBaseMetaData与Dom4j 实现Derby数据库中的表转换成xml文件,代码如下:

package com.bjsxt.jdbc;
import java.io.File;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class DatabaseMetaDataTest {
 public static void main(String[] args) throws Exception {
  Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
         System.out.println("Load the driver");
         Connection conn = null;
         Properties props = new Properties();
         props.put("user", "user1");  props.put("password", "user1");
         conn=DriverManager.getConnection("jdbc:derby:DerByDB;create=false", props);
         System.out.println("connect to DerByDB");
         DatabaseMetaData dbmd = conn.getMetaData();
         System.out.println("====getTables()方法====");
         ResultSet rs1 = dbmd.getTables(null, null, "STUDENT", new String[]{"TABLE"});
         while(rs1.next()) {    //其实结果集中只有一项,那就是TEACHER这个表。
         String tname=rs1.getString(3); //获取表名
         String ttype=rs1.getString(4);  //获取表类型
         Document document = DocumentHelper.createDocument(); //建立document对象 
         Element databaseElement = document.addElement("database");
         Element stuElement=databaseElement.addElement(tname);
         stuElement.addAttribute("表类型",ttype);
         try{
               OutputFormat opf=OutputFormat.createPrettyPrint();  //美化格式
               //解决中文乱码问题,在生成的xml文档声明中可以看到设置的编码。
               opf.setEncoding("gbk");   
               // 将document中的内容写入文件中
               XMLWriter writer = new XMLWriter(new FileWriter(new File("student.xml")),opf); 
               writer.write(document);
               writer.close();           
        
}catch(Exception ex){
               ex.printStackTrace();
        }
        }
        System.out.println("getTables is over");
        System.out.println("====getColumns()方法====");  

        //最后一个null表示取出所有的列
        ResultSet rs2 = dbmd.getColumns(null, null, "STUDENT", null); 
        while(rs2.next()) {                    
             String colName=rs2.getString(4);        //列名称
             int dataType = rs2.getInt("DATA_TYPE"); //数据类型
             String dt=null;
              if(dataType==Types.VARCHAR) {
                      dt="varchar";           
              }else if (dataType==Types.INTEGER) {
                      dt="int";
              }
              try {
                   SAXReader saxReader = new SAXReader();
                   Document document = saxReader.read("student.xml");            
                   Node node = document.selectSingleNode("//STUDENT");
                   Element studentElement = (Element)node;
                   studentElement.addElement(colName).setText(dt);
                   //美化格式,此时的xml文档多行书写
                   OutputFormat opf=OutputFormat.createPrettyPrint();
                   //解决中文乱码问题,在生成的xml文档声明中可以看到设置的编码。 
                   opf.setEncoding("gbk");
                   //将document中的内容写入文件中     
                   XMLWriter writer = new XMLWriter(new FileWriter("student.xml"),opf);
                   writer.write(document);
                   writer.close();             
               }catch (Exception e) {
                        e.printStackTrace();
               }
          }
         System.out.println("getColumns is over");
         System.out.println("====getPrimaryKeys()方法====");
         ResultSet rs3 =dbmd.getPrimaryKeys(null, null, "STUDENT");
         while(rs3.next()) {
         String  pname=rs3.getString(4);     //列名称
         System.out.println(pname);
          try {
                 SAXReader saxReader = new SAXReader();
                 Document document = saxReader.read("student.xml");
                 List<Node> list = document.selectNodes("//STUDENT");
                 Iterator<Node> iter=list.iterator();
                 while(iter.hasNext()){
                      Element studentElement = (Element)iter.next();
                      studentElement.addAttribute("primary", pname);
                 }                
//              Node node = document.selectSingleNode("//STUDENT");
//              Element studentElement = (Element)node;
//              studentElement.addAttribute("primary", pname);              
//              Node node = document.selectSingleNode("//STUDENT/@表类型");
//              Attribute stype = (Attribute)node;
//              stype.setValue("table");
//              Element studentElement = (Element)node;
                //美化格式,此时的xml文档多行书写
                OutputFormat opf=OutputFormat.createPrettyPrint();  
                //解决中文乱码问题,在生成的xml文档声明中可以看到设置的编码。  
                opf.setEncoding("gbk");      
                //将document中的内容写入文件中 
                XMLWriter writer = new XMLWriter(new FileWriter("student.xml"),opf); 
                writer.write(document);
                writer.close();
            }catch (Exception e) {
                e.printStackTrace();
            }         
         }
         rs1.close();
         rs2.close();
         rs3.close();
         conn.close();
         try {
             DriverManager.getConnection("jdbc:derby:;shutdown=true");
         } catch (SQLException se) {
                  System.out.println("Database shut down normally");
         }
     }
}

 

 


 

 

  • 6
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
package com.hexiang.utils; import java.sql.*; import java.util.*; /** * * Title: 数据库工具 * * * Description: 将大部分的数据库操作放入这个中, 包括数据库连接的建立, 自动释放等. * * * @author beansoft 日期: 2004年04月 * @version 2.0 */ public class DatabaseUtil { /** 数据库连接 */ private java.sql.Connection connection; /** * All database resources created by this class, should be free after all * operations, holds: ResultSet, Statement, PreparedStatement, etc. */ private ArrayList resourcesList = new ArrayList(5); public DatabaseUtil() { } /** 关闭数据库连接并释放所有数据库资源 */ public void close() { closeAllResources(); close(getConnection()); } /** * Close given connection. * * @param connection * Connection */ public static void close(Connection connection) { try { connection.close(); } catch (Exception ex) { System.err.println("Exception when close a connection: " + ex.getMessage()); } } /** * Close all resources created by this class. */ public void closeAllResources() { for (int i = 0; i < this.getResourcesList().size(); i++) { closeJDBCResource(getResourcesList().get(i)); } } /** * Close a jdbc resource, such as ResultSet, Statement, Connection.... All * these objects must have a method signature is void close(). * * @param resource - * jdbc resouce to close */ public void closeJDBCResource(Object resource) { try { Class clazz = resource.getClass(); java.lang.reflect.Method method = clazz.getMethod("close", null); method.invoke(resource, null); } catch (Exception e) { // e.printStackTrace(); } } /** * 执行 SELECT 等 SQL 语句并返回结果集. * * @param sql * 需要发送到数据库 SQL 语句 * @return a ResultSet object that contains the data produced * by the given query; never null */ public ResultSet executeQuery(String sql) { try { Statement statement = getStatement(); ResultSet rs = statement.executeQuery(sql); this.getResourcesList().add(rs); this.getResourcesList().add(statement);// BUG fix at 2006-04-29 by BeanSoft, added this to res list // MySql 数据库要求必需关闭 statement 对象, 否则释放不掉资源 // - 此观点错误, 因为关闭此对象后有时数据无法读出 //statement.close(); return rs; } catch (Exception ex) { System.out.println("Error in executeQuery(\"" + sql + "\"):" + ex); // ex.printStackTrace(); return null; } } /** * Executes the given SQL statement, which may be an INSERT, * UPDATE, or DELETE statement or an SQL * statement that returns nothing, such as an SQL DDL statement. 执行给定的 SQL * 语句, 这些语句可能是 INSERT, UPDATE 或者 DELETE 语句, 或者是一个不返回任何东西的 SQL 语句, 例如一个 SQL * DDL 语句. * * @param sql * an SQL INSERT,UPDATE or * DELETE statement or an SQL statement that * returns nothing * @return either the row count for INSERT, * UPDATE or DELETE statements, or * 0 for SQL statements that return nothing */ public int executeUpdate(String sql) { try { Statement statement = getStatement(); return statement.executeUpdate(sql); // MySql 数据库要求必需关闭 statement 对象, 否则释放不掉资源 // - 此观点错误, 因为关闭此对象后有时数据无法读出 //statement.close(); } catch (Exception ex) { System.out.println("Error in executeUpdate(): " + sql + " " + ex); //System.out.println("executeUpdate:" + sql); ex.printStackTrace(); } return -1; } /** * 返回记录总数, 使用方法: getAllCount("SELECT count(ID) from tableName") 2004-06-09 * 可滚动的 Statement 不能执行 SELECT MAX(ID) 之的查询语句(SQLServer 2000) * * @param sql * 需要执行的 SQL * @return 记录总数 */ public int getAllCount(String sql) { try { Statement statement = getConnection().createStatement(); this.getResourcesList().add(statement); ResultSet rs = statement.executeQuery(sql); rs.next(); int cnt = rs.getInt(1); rs.close(); try { statement.close(); this.getResourcesList().remove(statement); } catch (Exception ex) { ex.printStackTrace(); } return cnt; } catch (Exception ex) { System.out.println("Exception in DatabaseUtil.getAllCount(" + sql + "):" + ex); ex.printStackTrace(); return 0; } } /** * 返回当前数据库连接. */ public java.sql.Connection getConnection() { return connection; } /** * 连接新的数据库对象到这个工具, 首先尝试关闭老连接. */ public void setConnection(java.sql.Connection connection) { if (this.connection != null) { try { getConnection().close(); } catch (Exception ex) { } } this.connection = connection; } /** * Create a common statement from the database connection and return it. * * @return Statement */ public Statement getStatement() { // 首先尝试获取可滚动的 Statement, 然后才是普通 Statement Statement updatableStmt = getUpdatableStatement(); if (updatableStmt != null) return updatableStmt; try { Statement statement = getConnection().createStatement(); this.getResourcesList().add(statement); return statement; } catch (Exception ex) { System.out.println("Error in getStatement(): " + ex); } return null; } /** * Create a updatable and scrollable statement from the database connection * and return it. * * @return Statement */ public Statement getUpdatableStatement() { try { Statement statement = getConnection() .createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); this.getResourcesList().add(statement); return statement; } catch (Exception ex) { System.out.println("Error in getUpdatableStatement(): " + ex); } return null; } /** * Create a prepared statement and return it. * * @param sql * String SQL to prepare * @throws SQLException * any database exception * @return PreparedStatement the prepared statement */ public PreparedStatement getPreparedStatement(String sql) throws SQLException { try { PreparedStatement preparedStatement = getConnection() .prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); this.getResourcesList().add(preparedStatement); return preparedStatement; } catch (Exception ex) { ex.printStackTrace(); } return null; } /** * Return the resources list of this class. * * @return ArrayList the resources list */ public ArrayList getResourcesList() { return resourcesList; } /** * Fetch a string from the result set, and avoid return a null string. * * @param rs * the ResultSet * @param columnName * the column name * @return the fetched string */ public static String getString(ResultSet rs, String columnName) { try { String result = rs.getString(columnName); if (result == null) { result = ""; } return result; } catch (Exception ex) { } return ""; } /** * Get all the column labels * * @param resultSet * ResultSet * @return String[] */ public static String[] getColumns(ResultSet resultSet) { if (resultSet == null) { return null; } try { ResultSetMetaData metaData = resultSet.getMetaData(); int numberOfColumns = metaData.getColumnCount(); if (numberOfColumns <= 0) { return null; } String[] columns = new String[numberOfColumns]; //System.err.println("numberOfColumns=" + numberOfColumns); // Get the column names for (int column = 0; column < numberOfColumns; column++) { // System.out.print(metaData.getColumnLabel(column + 1) + "\t"); columns[column] = metaData.getColumnName(column + 1); } return columns; } catch (Exception ex) { ex.printStackTrace(); } return null; } /** * Get the row count of the result set. * * @param resultset * ResultSet * @throws SQLException * if a database access error occurs or the result set type is * TYPE_FORWARD_ONLY * @return int the row count * @since 1.2 */ public static int getRowCount(ResultSet resultset) throws SQLException { int row = 0; try { int currentRow = resultset.getRow(); // Remember old row position resultset.last(); row = resultset.getRow(); if (currentRow > 0) { resultset.absolute(row); } } catch (Exception ex) { ex.printStackTrace(); } return row; } /** * Get the column count of the result set. * * @param resultSet * ResultSet * @return int the column count */ public static int getColumnCount(ResultSet resultSet) { if (resultSet == null) { return 0; } try { ResultSetMetaData metaData = resultSet.getMetaData(); int numberOfColumns = metaData.getColumnCount(); return numberOfColumns; } catch (Exception ex) { ex.printStackTrace(); } return 0; } /** * Read one row's data from result set automatically and put the result it a * hashtable. Stored as "columnName" = "value", where value is converted to * String. * * @param resultSet * ResultSet * @return Hashtable */ public static final Hashtable readResultToHashtable(ResultSet resultSet) { if (resultSet == null) { return null; } Hashtable resultHash = new Hashtable(); try { String[] columns = getColumns(resultSet); if (columns != null) { // Read data column by column for (int i = 0; i < columns.length; i++) { resultHash.put(columns[i], getString(resultSet, columns[i])); } } } catch (Exception ex) { ex.printStackTrace(); } return resultHash; } /** * Read data from result set automatically and put the result it a * hashtable. Stored as "columnName" = "value", where value is converted to * String. * * Note: assume the default database string encoding is ISO8859-1. * * @param resultSet * ResultSet * @return Hashtable */ @SuppressWarnings("unchecked") public static final Hashtable readResultToHashtableISO(ResultSet resultSet) { if (resultSet == null) { return null; } Hashtable resultHash = new Hashtable(); try { String[] columns = getColumns(resultSet); if (columns != null) { // Read data column by column for (int i = 0; i < columns.length; i++) { String isoString = getString(resultSet, columns[i]); try { resultHash.put(columns[i], new String(isoString .getBytes("ISO8859-1"), "GBK")); } catch (Exception ex) { resultHash.put(columns[i], isoString); } } } } catch (Exception ex) { ex.printStackTrace(); } return resultHash; } /** Test this class. */ public static void main(String[] args) throws Exception { DatabaseUtil util = new DatabaseUtil(); // TODO: 从连接池工厂获取连接 // util.setConnection(ConnectionFactory.getConnection()); ResultSet rs = util.executeQuery("SELECT * FROM e_hyx_trans_info"); while (rs.next()) { Hashtable hash = readResultToHashtableISO(rs); Enumeration keys = hash.keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); System.out.println(key + "=" + hash.get(key)); } } rs.close(); util.close(); } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值