在项目的开发过程中,数据字典的维护是一件烦琐的事情.所以我写了一段代码来自动生成数据字典.
其中用到Jakarta POI,这是一个用于访问Microsoft Format Files的开源项目,详细信息请看这里.
http://jakarta.apache.org/poi/index.html
下面是程序的源代码及说明
import java.io.*;
import java.sql.*;
import org.apache.poi.hssf.usermodel.*;
public class AppMain {
public AppMain() {
}
public static void main(String[] args) {
try {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet =null;
/**连接ORACLE的数据库,关键在于两个系统级的VIEW:
all_tab_columns 记录着ORACLE所有的字段定义信息.
DBA_COL_COMMENTS 记录着字段的注释信息,*/
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@127.0.0.1:1521:ORACLE", "用户名", "密码");
Statement stmt = con.createStatement();
StringBuffer strbuf = new StringBuffer();
strbuf.append("SELECT A.*,B.comments");
strbuf.append(" FROM all_tab_columns A,DBA_COL_COMMENTS B");
strbuf.append(" WHERE A.owner=B.owner");
strbuf.append(" AND A.table_name=B.table_name");
strbuf.append(" AND A.COLUMN_NAME=B.COLUMN_NAME");
//owner是建立表的用户名
strbuf.append(" AND A.owner=myuser");
strbuf.append(" ORDER BY A.TABLE_NAME");
ResultSet rs = stmt.executeQuery(strbuf.toString());
String tb = "";
int k = 0;
while (rs.next()) {
//对每个表生成一个新的sheet,并以表名命名
if (!tb.equals(rs.getString("TABLE_NAME"))) {
sheet = wb.createSheet(rs.getString("TABLE_NAME"));
//设置表头的说明
HSSFRow row = sheet.createRow(0);
setCellGBKValue(row.createCell((short) 0),"字段名");
setCellGBKValue(row.createCell((short) 1),"字段类型");
setCellGBKValue(row.createCell((short) 2),"字段长度");
setCellGBKValue(row.createCell((short) 3),"数字长度");
setCellGBKValue(row.createCell((short) 4),"小数位数");
setCellGBKValue(row.createCell((short) 5),"能否为NULL");
setCellGBKValue(row.createCell((short) 6),"字段说明");
k = 1;
} else {
k++;
}
tb = rs.getString("TABLE_NAME");
HSSFRow row = sheet.createRow(k);
row.createCell((short) 0).setCellValue(rs.getString(
"COLUMN_NAME"));
row.createCell((short) 1).setCellValue(rs.getString("DATA_TYPE"));
row.createCell((short) 2).setCellValue(rs.getString(
"DATA_LENGTH"));
row.createCell((short) 3).setCellValue(rs.getString(
"DATA_PRECISION"));
row.createCell((short) 4).setCellValue(rs.getString(
"DATA_SCALE"));
row.createCell((short) 5).setCellValue(rs.getString("NULLABLE"));
setCellGBKValue(row.createCell((short) 6),rs.getString("COMMENTS"));
}
//把生成的EXCEL文件输出保存
FileOutputStream fileOut = new FileOutputStream("F:\\数据字典.xls");
wb.write(fileOut);
fileOut.close();
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
这个函数是为了设置一个CELL为中文字符串
*/
private static void setCellGBKValue(HSSFCell cell, String value) {
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
//设置CELL的编码信息
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(value);
}
}
这样运行这段代码后,就会生成一个数据字典.如果需要,可以对选择的信息做修改,
只需要修改相关的对ORACLE系统表或者视图的SELECT语句即可.
本文可以自由转载,但请注明出处.