怎么获得数据库表结构

/**
     * 获取表结构信息
     * @param tableName 表名
     * @return
     * @throws Exception
     * Method create author: yanwei
     * Method create dateTime: 2011-12-21 下午01:01:17
     * Method update author:
     * Method update dateTime:
*/
    public List<DsClientColumnInfo> getDsTableColumnInfo(String tableName) throws DataAccessFailureException{
        
        ResultSet resultSet = null;
        Connection connection = null;
        java.util.List<DsClientColumnInfo> clientTableInfos = new ArrayList<DsClientColumnInfo>();
        try {
            connection = this.jdbcTemplate.getDataSource().getConnection();
            //获得列的信息
            resultSet = connection.getMetaData().getColumns(null, null, tableName, null);
            while (resultSet.next()) {
                 //获得字段名称
                 String name = resultSet.getString("COLUMN_NAME");
                 //获得字段类型名称
                 String type = resultSet.getString("TYPE_NAME");
                 //获得字段大小
                 int size = resultSet.getInt("COLUMN_SIZE");
                 //获得字段备注
                 String remark = resultSet.getString("REMARKS");
                 DsClientColumnInfo info = new DsClientColumnInfo(null, null, null, name, remark, size, type, "false");
                 clientTableInfos.add(info);
            }
            
            //获得主键的信息
            resultSet = connection.getMetaData().getPrimaryKeys(null, null, tableName);
            while(resultSet.next()){
                 String  primaryKey = resultSet.getString("COLUMN_NAME");
                 //设置是否为主键
                 for (DsClientColumnInfo dsClientColumnInfo : clientTableInfos) {
                    if(primaryKey != null && primaryKey.equals(dsClientColumnInfo.getClientColumnCode()))
                        dsClientColumnInfo.setIsParmaryKey("true");
                    else 
                        dsClientColumnInfo.setIsParmaryKey("false");
                }
            }
            
            //获得外键信息
            resultSet = connection.getMetaData().getImportedKeys(null, null, tableName);
            while(resultSet.next()){
                String  exportedKey = resultSet.getString("FKCOLUMN_NAME");
                //设置是否是外键
                 for (DsClientColumnInfo dsClientColumnInfo : clientTableInfos) {
                        if(exportedKey != null && exportedKey.equals(dsClientColumnInfo.getClientColumnCode()))
                            dsClientColumnInfo.setIsImportedKey("true");
                        else 
                            dsClientColumnInfo.setIsImportedKey("false");
                }
            }
            
            
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取字段信息的时候失败,请将问题反映到维护人员。" + e.getMessage(), e);
        } finally{
            if(resultSet != null)
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                       throw new DataAccessFailureException("关闭结果集resultSet失败。",e);
                }finally{
                    if(connection != null)
                        try {
                            connection.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                               throw new DataAccessFailureException("关闭连接connection失败。",e);
                        }
                }
        }
        
        Set set = new HashSet();
        set.addAll(clientTableInfos);
        clientTableInfos.clear();
        clientTableInfos.addAll(set);
        return clientTableInfos;

    }


//获取数据库下所有表

/**
     * 获得数据库中所有的表
     * @return
     * Method create author: yanwei
     * Method create dateTime: 2012-1-5 上午11:23:54
     * Method update author:
     * Method update dateTime:
     * @throws SQLException 
*/
    public Map<String, String> getDatabaseTables() throws DataAccessFailureException{
        ResultSet resultSet = null;
        Connection connection = null;
        Map<String, String> map = new HashMap<String, String>();
        try {
             String[]   types   =   {"TABLE"};    
            connection = this.jdbcTemplate.getDataSource().getConnection();
            String databaseName = SynXmlAnalysis.getElementValueByName(DATABASE_NAME);
            resultSet = connection.getMetaData().getTables(null, databaseName, null, types);
            while(resultSet.next()){
                String tableName = resultSet.getString("TABLE_NAME");
                String remark = resultSet.getString("REMARKS");
                map.put(tableName, remark);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new DataAccessFailureException(e);
        }catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(resultSet != null)
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                       throw new DataAccessFailureException("关闭结果集resultSet失败。",e);
                }finally{
                    if(connection != null)
                        try {
                            connection.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                               throw new DataAccessFailureException("关闭连接connection失败。",e);
                        }
                }
        
        }
        return map;
    }



JDBC应用心得

1 当我需要从数据库中获得一个精确的大数(超过FLOAT的表示范围)应该怎么做?
使用BigDecimal类。该类能支持2147483647位的数字,无论精度还是范围都是32位无符号整数。


2 我想限定查询结果的数目,应该怎么做?
使用Statement的setMaxRows(int number)方法。该方法可以只选出number个结果。并将结果集中多余的部分丢弃。


3 我想限定结果集中字符串结果的字段长度(或者其他类型结果的大小),应该怎么做?
使用Statement的setMxFiledSize(int number)方法,该方法可以限定结果集的字段长度,在使用该方法后,

任何超过该长度的字段都将被丢弃。注意,当为0时则被定义为无大小限制。
该方法只能用与具有如下格式SQL格式的数据:
binary,varbinary,longvarbinary,char,vachar,longvarchar


4 我如何查询有关数据库响应超时?
使用Statement的setQueyTimeout(int number)方法。该方法(number)以秒为单位。注意,当为0的时候,

表示一个查询可以使用的查询时间是无限的。


5 我如何创建一个可滚动的ResultSet对象?
为了创建一个可滚动的ResultSet对象,需要使用creatStatement()方法的另外一种格式

(注意,该格式只适用于JDBC2.0)。
Statement createStatement(int resultSetType,int resultSetConcurrency)
其中,具体的参数及说明如下:
resultSetType-----
ResultSet.TYPE_FORWARD_ONLY
ResultSet.TYPE_SCROLL_INSENSITIVE
ResultSet.TYPE.SCROLL.SENSITIVE
当使用ResultSet.TYPE_FORWARD_ONLY时(该属性为createStatement()默认属性)

则表示产生一个只能前移的Result对象。
而另外两种属性则可以实现游标在该结果集中的向前或向后移动。

其中ResultSet.TYPE_SCROLL_INSENSITIVE对象不受事务对象底层数据库所做的修改。

而一个ResultSet.TYPE.SCROLL.SENSITIVE对象则可见事务对底层数据库的修改。


ResultSetConcurrency-----
CONCUR_READ_ONLY
CONCUR_UPDATABLE
CONCUR_UPDATABLE属性表示可以在结果集中修改和创建数据。


6 我如何使游标可以在结果集中移动?
当设置了ResultSet.TYPE_SCROLL_INSENSITIVE或ResultSet.TYPE.SCROLL.SENSITIVE属性后,

定义一个游标在结果集中的移动可以使用Result的如下的方法:
Boolean preivoue()---移动到前一行
Boolean first()---移动最初一行
Boolean last()---移动到最后一行
Boolean next()---移动到下一行
Boolean absolute(int number)---转移第number行数据
Boolean relative(int number)---从当前行开始移动number行
Void afterlast()---移动到数据集底
Void beforefirst()---移动到数据集的开始(注意和first()的区别)
Boolean isFirsr()---判断是否为数据集中第一个数据
Boolean isBeforeFirst()---判断是否为数据集的开始
Boolean isLast()---判断是否为数据集的最后一个数据
Boolean isAfterLast()---判断是否为数据集的最后
Int getRow()---获得结果集的数目
Void moveToInsertRow()---移动到一个用于结果集插入的特殊行
Void moveToCurrentRow()---调离已插入行,回到数据集中待插入之前的行


7 我该如何创建一个可更新的Result对象

(我需要在查询结果集中修改数据,但我又不想创建过多的Statement对象)?
首先你的查询数据库SQL必须满足如下的条件:
。只引用单个的表
。不含有一个join或者group by子句
。选择主关键字作为那些列之一
然后将Statement createStatement(int resultSetType,int resultSetConcurrency)

中的int resultSetConcurrency 属性设置为CONCUR_UPDATABLE
OK,这样你就可以利用如下方法修改或者添加你的结果集中的数据了:
updateString(),updateBoolean(),updateByte(),

updateShort(),updateInt(),updateDatelong(),updateFloat(),
updateFloat(),updateDouble(),updateBigDecimal(),

updateBytes(),updateDate(),updateTime()
updateTimeStamp(),updateAsciiStream(),

updateCharacterStream(),updateBinaryStream(),

updatedateNull()
updateObject()
在使用完如上方法之后,则需要调用相应的
Result.insertRow(),或者Result.updateRow()方法以将插入或者修改存如数据库。


8 在不访问系统表的情况下,用什么方法可以得到数据库的基本信息?
使用元数据。
具体创建如下:

Connection conn = ConnnectionFactory.getConnection ();
DatabaseMetaData dbmseeage = coon . getMetaData () ;
以下是几个比较常用的元数据的例子:
dbmseeage .getDatabaseProductName()---得到数据库名字
dbmseeage .getDatabaseProductVersion()---得到数据库的版本
dbmseeage .getDriverName()---得到所使用的驱动的名字
dbmseeage .getDriverVersion()---得到所使用驱动的版本


9 我如何获得数据库中所有的表名?
使用元数据。
具体创建方式见 8
dbmessage.getTables (null,null,null,types)
有关以上函数的具体分析如下:
dbmessage.getTables ( String catalog,String schema,String tablename,String[] types)
String catalog---指出该方法从给定的编目中获得表,如果为空,则从所有编目
String chema---指出该方法应该从给定的架构下获得表,如果为空,则从所有架构
String tablename---指出该方法应该返回与该参数匹配的表项,

其中可以包括表示单字符的通配符下划线,以及表示多字符的通配符百分号。


10 我如何获得某一个表的结构信息呢?
使用元数据。
具体的创建方法见 8 , 9

ResultSet columns = dbmessage .getColumns(null,null,[tablename],null)
While(coulumns.next()){
columns.getString (“COLUMN_NAME”)---得到列名
columns.getString(“DATA_TYPE”)---得到列的类型
columns.getString(“COLUMN_SIZE”)---得到列中数据的大小
columns.getString(“IS_NULLABLE”)---该列是否为空
}
ResultSet pkeys = dbmessage .getPrimaryKeys(null,null,[tablename])
Pkeys.getString(“COLUM_NAME”)---得到作为内键的列名


11 使用方法 10 并不能得到有关递增列的信息,我该如何获取该信息?
使用元数据。但需要创建与9,10不同的元数据。
具体的创建方法如下:
Connection conn = ConnnectionFactory.getConnection ();
Statement smt=conn.crtateStatement();
Result result = smt.excute Query(“sel;ect * from [tablename]”);
ResultSetMetaData rmd=result.getMetaData();
Int cols = rmd.getColumnCount();
使用方法如下:
For(int i=1;i<cols;i++){
If (rmd.isAutoIncrement(i))
   {
   System.out.println(“The column :”+rmd.getColunmName(i)+ “ is autoincreaced”);
   }
}
使用该方法可以得到递增列的列名。如果需要得到其他信息,则可以配合 9,10


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值