Topic: Groovy+DbUnit 轻松实现数据库导入导出

  Print this page

1.Groovy+DbUnit 轻松实现数据库导入导出 Copy to clipboard
Posted by: Jove
Posted on: 2004-11-08 09:58

http://dbunit.sf.net 是一个方便好用的JUnit扩展,在每个TestCase test方法执行前后可以做数据库初始化和善后工作
也可以单独使用它的这一功能作数据导入和导出。
与数据库通常自带的备份功能(比如DB2)不同
它使用JDBC来读取数据和元数据,不需要关闭数据库作停机备份
它导出的格式可以是XML格式,方便阅读和编辑

http://groovy.codehaus.org 是一个强大而简洁的脚本语言
这里我们使用它来调用DbUnit,可以方便的更改设置(如数据库连接信息,所选数据集等)

下面给出三个脚本,分别是数据导出,导入,和生成DTD。 代码比较简单,即使没用过DbUnit和Groovy也应该可以大致看明白
以数据导出为例,脚本一开始给出若干设置
用户可以选择导出整个数据库,或是一个列表中的数据表(在代码中指定,或弹出对话框指定)
也可以选择保存文件的路径

使用方法简单介绍:
按照Groovy网站上的信息下载并安装Groovy,下载DbUnit,把dbunit-2.1.jar放入GROOVY_HOME/lib
把所用的JDBC Driver如db2jcc.jar等放入GROOVY_HOME/lib
打开cmd或term, 执行groovy filename

export.groovy
import groovy.sql.Sql
import java.io.*
import java.awt.*
import javax.swing.*
import org.dbunit.database.*
import org.dbunit.dataset.*
import org.dbunit.dataset.xml.*

#JDBC Connection
url  ='jdbc:db2://9.181.106.179:50000/SAMPLE'
driver  ='com.ibm.db2.jcc.DB2Driver'
user  ='db2admin'
pwd  ='db2admin'

#if gui=true,show a fileSaveDialog to select a file to save;otherwise use 'defaultFile'
gui=true
chooserInitDir='.'
defaultFile='data.xml'

#Three modes:
# 0:export all tables
# 1:export tables in a specified list
# 2:Show a dialog to select tables to export
exportType=2
tableList=['JOVE.NB_USER','JOVE.NB_FOOD','JOVE.NB_BOOKING']

#Main method
file=getFileToSave()
sql=Sql.newInstance(url,user,pwd,driver)
jdbcConnection=sql.getConnection()
con = new DatabaseConnection(jdbcConnection)
con.getConfig().setFeature("http://www.dbunit.org/features/qualifiedTableNames", true)
println 'Reading data and saving..\n'  
switch(exportType){
case 0:dataset=exportAll(con);break;
case 1:dataset=exportTables(con,tableList);break;
default:dataset=exportSelected(con)
}
FlatXmlDataSet.write(dataset, new FileOutputStream(file))
println "Data is saved in ${file}.\n---Press any key to quit---"
System.in.read()
System.exit(0)

def getFileToSave(){
  if(gui){
    chooser=new JFileChooser(chooserInitDir)
    chooser.setDialogTitle("Save the exported dataset to")
    if(chooser.showSaveDialog() == JFileChooser.APPROVE_OPTION)
      return chooser.getSelectedFile()   
    else
      System.exit(0)
  }else
    return defaultFile
}

def exportAll(connection) {
  return connection.createDataSet()
}

def exportTables(connection,tableList){
  dataset=new QueryDataSet(connection)
  for(table in tableList)
    dataset.addTable(table)
  return dataset  
}

def exportSelected(connection){
  tables=connection.createDataSet().getTableNames()
  itemList=new JList(tables)
  itemList.selectionMode = ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
  JOptionPane.showMessageDialog(null,new JScrollPane(itemList),
    'Select Database Tables',JOptionPane.QUESTION_MESSAGE)
  return exportTables(connection,itemList.getSelectedValues())  
}

import.groovy
import groovy.sql.Sql
import java.io.File
import javax.swing.JFileChooser
import org.dbunit.database.*
import org.dbunit.dataset.*
import org.dbunit.dataset.xml.*
import org.dbunit.operation.DatabaseOperation

gui=false
if(gui){
  initDir="."
  chooser=new JFileChooser(initDir);
  chooser.setDialogTitle("Select xml file to import")
  if(chooser.showOpenDialog() == JFileChooser.APPROVE_OPTION)
    file=chooser.getSelectedFile()   
  else
    System.exit(0)
}else
  file=new File("kiss.data.xml")

url  ='jdbc:db2://9.181.106.179:50000/SAMPLE'
driver  ='com.ibm.db2.jcc.DB2Driver'
user  ='db2admin'
pwd  ='db2admin'
sql=Sql.newInstance(url,user,pwd,driver)
jdbcConnection=sql.getConnection()
con = new DatabaseConnection(jdbcConnection)
con.getConfig().setFeature("http://www.dbunit.org/features/qualifiedTableNames", true)

dataSet = new FlatXmlDataSet(file);
DatabaseOperation.CLEAN_INSERT.execute(con, dataSet);
println "Done.\n---Press any key to quit---"

System.in.read()
System.exit(0)

exportDtd.groovy
import groovy.sql.Sql
import java.io.*
import javax.swing.JFileChooser
import org.dbunit.database.*
import org.dbunit.dataset.*
import org.dbunit.dataset.xml.*

gui=false
if(gui){
  initDir="."
  chooser=new JFileChooser(initDir)
  chooser.setDialogTitle("Save the exported DTD to")
  if(chooser.showSaveDialog() == JFileChooser.APPROVE_OPTION)
    file=chooser.getSelectedFile()   
  else
    System.exit(0)
}else
  file="kiss.data.dtd"

url  ='jdbc:db2://9.181.106.179:50000/SAMPLE'
driver  ='com.ibm.db2.jcc.DB2Driver'
user  ='db2admin'
pwd  ='db2admin'
sql=Sql.newInstance(url,user,pwd,driver)
jdbcConnection=sql.getConnection()
con = new DatabaseConnection(jdbcConnection)
con.getConfig().setFeature("http://www.dbunit.org/features/qualifiedTableNames", true)
println 'Reading data and saving..'  
// write DTD file
FlatDtdDataSet.write(con.createDataSet(),new FileOutputStream(file));

println "Done.\n---Press any key to quit---"
System.in.read()
System.exit(0)

2.Re:Groovy+DbUnit 轻松实现数据库导入导出 [Re: Jove] Copy to clipboard
Posted by: Jove
Posted on: 2004-11-08 10:17

第一次用Groovy,大家给点意见 Smile

3.Re:Groovy+DbUnit 轻松实现数据库导入导出 [Re: Jove] Copy to clipboard
Posted by: javait
Posted on: 2004-11-09 10:10

COOL!CoolCool
如果只是数据导入和导出,也可以用纯JDBC中的METADATA,来产生脚本文件。

-JAVAIT

4.Re:Groovy+DbUnit 轻松实现数据库导入导出 [Re: javait] Copy to clipboard
Posted by: Jove
Posted on: 2004-11-09 11:03

DbUnit就是用JDBC去读metadata
既然有人已经做这些工作,就不必什么都自己写了
如果需要ddl,可以写个xslt或什么程序转一下

用现成lib和脚本语言的乐趣就是用很少的代码完成一件看似比较麻烦的事情 Big Smile


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923