利用Groovy对数据库进行操作是极其方便的,有时为了熟悉数据库中的表,需要将表结构导出,并保存为EXCEL格式。
下面所展示的源代码就能够很好的满足我们的需求。(这段代码依赖jxl和Oracle的jdbc驱动)
功能保持不变的条件下,代码做了一些小调整,利用Groovy中的强大特性Mixin,使代码更优雅。
导出效果:
conf.properties
filename=table_structures.xls
tables.to.export=%
column.width=15
url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
user=DANIEL
password=123456
driver=oracle.jdbc.driver.OracleDriver
GroovySql.groovy
/*
* Copyright 2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Auth
*/
import groovy.sql.Sql
import jxl. *
import jxl.write. *
Properties properties = new Properties();
properties.load( new FileInputStream( " conf.properties " ));
def filename = properties.getProperty( ' filename ' )
def tablesToExport = properties.getProperty( ' tables.to.export ' )
def columnWidth = properties.getProperty( ' column.width ' )
def url = properties.getProperty( ' url ' )
def user = properties.getProperty( ' user ' )
def password = properties.getProperty( ' password ' )
def driver = properties.getProperty( ' driver ' )
def sql = Sql.newInstance(url, user, password, driver)
def sqlStmt = """
select
a.table_name,
a.column_name,
(select
d.constraint_type
from
all_constraints d,
all_cons_columns e
where
c.owner = d.owner and
d.owner = e.owner and
c.table_name = d.table_name and
d.table_name = e.table_name and
b.column_name = e.column_name and
d.constraint_name = e.constraint_name and
d.constraint_type = ' P ' and
rownum = 1
) as constraint_type,
a.data_type,
a.data_length,
a.data_precision,
a.data_scale,
a.nullable,
a.data_default,
b.comments,
c.comments as tab_comments
from
all_tab_columns a,
all_col_comments b,
all_tab_comments c
where