首页 > 代码库 > 从oracle数据库导出数据(表结构,表数据,视图,存储过程,序列)

从oracle数据库导出数据(表结构,表数据,视图,存储过程,序列)

package com.ahzysoft.export;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;




import com.ibatis.sqlmap.client.SqlMapSession;

/**
 * 导出oracle数据库表的表结构,表数据,视图,表的存储过程
 */
public class Export {
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public String export(){
        String result = "导出成功";
        String ddl = "";
        String insertString = "";
        String insertString1 = "";
        String sql = "";
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Tables> listTable = new  ArrayList<Tables>();
        List<Tables> listView = new  ArrayList<Tables>();
        List<Tables> listProcedure = new  ArrayList<Tables>();
        List<Tables> listProcedureText = new  ArrayList<Tables>();
        List<Tables> listSequences = new  ArrayList<Tables>();
        SqlMapSession session = null;
        Connection conn = null;
        try {
            session = IbatisUtil.getSqlMapSession();
            conn = session.getDataSource().getConnection();
            Statement stat = conn.createStatement();
            File file = new File("D:\\22222.txt");
            PrintStream ps = new PrintStream(new FileOutputStream(file));
            listTable = session.queryForList("table.selTablename");//查询当前用户所拥有的表
            listView = session.queryForList("table.selViewname");//查询当前用户所拥有的视图
            listProcedure = session.queryForList("table.selObjectname");//查询存储过程
            listSequences = session.queryForList("table.selSequences");//查询序列
            if(listTable.size()>0){
                Map map = new HashMap();
                
                //循环表,获取表的DDL语言
                for(Tables table:listTable){
                    map.put("table",table.getTable_name());
                    sql = "select * from dba_tab_columns where table_name=‘"+table.getTable_name()+"‘";
                    ResultSet rs1 = stat.executeQuery(sql);//根据表名查询列
                    sql = "select * from "+table.getTable_name();
                    ResultSet rs2 = stat.executeQuery(sql);//根据表名查询所有记录
                    ddl = (String) session.queryForObject("table.selTableddl",map);//根据表名获取ddl
                    
                    
                    /**
                     * 截取DDL有用的部分,边读边写ddl
                     */
                    int index = ddl.indexOf("SEGMENT CREATION");
                    if(index!=-1){
                        ps.append(ddl.substring(0,index)+";");
                        ps.append("\r\n");//换行继续
                        ps.append("\r\n");//换行继续
                    }
                    
                    /**
                     * 获取insert语句,并写入文件中
                     */
                    ResultSetMetaData rsmd = rs1.getMetaData();
                    String[] collumName = DbUtil.getColumnName(rsmd);
                    int[] columnType = DbUtil.getColumnType(rsmd);
                    insertString1 = "insert into "+table.getTable_name()+"(";
                    for(int i=0;i<collumName.length;i++){
                        insertString1 = insertString1+collumName[i]+",";
                    }
                    insertString1 = insertString1.substring(0, insertString1.length()-1)+")values(";
                    while(rs2.next()){
                        insertString = insertString1;
                        for(int j=0;j<collumName.length;j++){
                            if(columnType[j] == Type.INTEGER){
                                insertString = insertString + rs2.getInt(collumName[j])+",";
                            }else if(columnType[j] == Type.DOUBLE){
                                insertString = insertString + rs2.getDouble(collumName[j])+",";
                            }else if(columnType[j] == Type.DATETIME){
                                if(rs2.getTimestamp(collumName[j])==null){
                                    insertString = insertString + "null,";
                                }else{
                                    String date = sdf.format(rs2.getTimestamp(collumName[j]));
                                    date = date.replaceAll("-","");
                                    insertString = insertString +"to_date(‘"+ date+"‘,‘YYYYMMDD HH24:MI:SS‘),";//插入oracle数据库时间字段的格式
                                }
                            }else{
                                insertString = insertString +"‘"+ rs2.getString(collumName[j])+"‘,";
                            }
                        }
                        insertString = insertString.substring(0, insertString.length()-1)+");";
                        ps.append(insertString);
                        ps.append("\r\n");
                        ps.append("\r\n");
                    }
                }
            }
            
            /**
             * 获取创建view的语句,并写入文件中
             */
            if(listView.size()>0){
                for(Tables view:listView){
                    String viewString = "create view "+ view.getView_name() +" AS ";
                    viewString = viewString + view.getText()+";";
                    ps.append(viewString);
                    ps.append("\r\n");
                    ps.append("\r\n");
                }
            }
            
            /**
             * 获取存储过程的语句,并写入文件中
             */
             if(listProcedure.size()>0){
                for(Tables procedure:listProcedure){//循环存储过程,在通过存储过程名称查询存储过程内容
                    String procedureTextString = "";
                    listProcedureText = session.queryForList("table.selObjecttextByname", procedure.getObject_name());
                    if(listProcedureText.size()>0){//循环存储内容拼接成字符串
                        for(Tables proceduretext:listProcedureText){
                            procedureTextString = procedureTextString + proceduretext.getText()+"\r\n";
                        }
                        char c = procedureTextString.charAt(0);
                        if((int)c>=97){
                            procedureTextString = procedureTextString.replace("procedure","create or replace procedure");
                        }else{
                            procedureTextString = procedureTextString.replace("PROCEDURE","create or replace procedure");
                        }
                        
                        ps.append(procedureTextString+";");
                        ps.append("\r\n");
                        ps.append("\r\n");
                    }
                    
                }
            }
             
             /**
             * 获取序列语句,并写入文件中
             */
             if(listSequences.size()>0){
                 for(Tables sequence:listSequences){
                     String sequencesText = "CREATE SEQUENCE "+sequence.getSequence_name()+"  MINVALUE "+sequence.getMin_value()+" MAXVALUE "+sequence.getMax_value()+
                             " INCREMENT BY "+sequence.getIncrement_by()+" START WITH "+sequence.getLast_number()+" CACHE "+sequence.getCache_size()+";"; 
                     ps.append(sequencesText);
                     ps.append("\r\n");
                    ps.append("\r\n");
                 }
             }
             
            stat.close();
            ps.close();
        } catch (SQLException e) {
            result = "导出错误";
            e.printStackTrace();
        }catch (FileNotFoundException e) {
            result = "导出错误";
            e.printStackTrace();
        }
        finally{
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            session.close();
        }
        return result;
    }
    
    public static void main(String[] args) {
        String result = "";
        Export ex = new Export();
        result = ex.export();
        System.out.println(result);
    }
}

此段代码,可以导出oracle数据库中一个用户下的所以的表的表结构语句,表数据的insert语句,序列的create语句,存储过程的语句,视图的语句,全部整个到一个txt中,之后直接复制txt的内容,就能直接执行,进行数据库的复制!

上面的是导出类:Export.java

下面附上一些辅助类:

Tables.java      此类中的字段主要是根据数据库的字段而定

package com.ahzysoft.export;

public class Tables {
    private String table_name;
    private String view_name;
    private String owner;
    private String text;
    private String object_name;
    private String sequence_name;
    private long min_value;
    private String max_value;
    private long last_number;
    private long increment_by;
    private String cycle_flag;
    private String order_flag;
    private long cache_size;
    

    public String getTable_name() {
        return table_name;
    }

    public void setTable_name(String table_name) {
        this.table_name = table_name;
    }

    public String getView_name() {
        return view_name;
    }

    public void setView_name(String view_name) {
        this.view_name = view_name;
    }

    public String getOwner() {
        return owner;
    }

    public void setOwner(String owner) {
        this.owner = owner;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public String getObject_name() {
        return object_name;
    }

    public void setObject_name(String object_name) {
        this.object_name = object_name;
    }

    public String getSequence_name() {
        return sequence_name;
    }

    public void setSequence_name(String sequence_name) {
        this.sequence_name = sequence_name;
    }

    public long getMin_value() {
        return min_value;
    }

    public void setMin_value(long min_value) {
        this.min_value =http://www.mamicode.com/ min_value;
    }

    public String getMax_value() {
        return max_value;
    }

    public void setMax_value(String max_value) {
        this.max_value =http://www.mamicode.com/ max_value;
    }

    public long getLast_number() {
        return last_number;
    }

    public void setLast_number(long last_number) {
        this.last_number = last_number;
    }

    public long getIncrement_by() {
        return increment_by;
    }

    public void setIncrement_by(long increment_by) {
        this.increment_by = increment_by;
    }

    public String getCycle_flag() {
        return cycle_flag;
    }

    public void setCycle_flag(String cycle_flag) {
        this.cycle_flag = cycle_flag;
    }

    public String getOrder_flag() {
        return order_flag;
    }

    public void setOrder_flag(String order_flag) {
        this.order_flag = order_flag;
    }

    public long getCache_size() {
        return cache_size;
    }

    public void setCache_size(long cache_size) {
        this.cache_size = cache_size;
    }

    
    
}

Type.java

package com.ahzysoft.export;

public class Type {
      public static final int INTEGER = 1;
      public static final int DOUBLE = 2;
      public static final int STRING = 3;
      public static final int DATETIME = 4;
}

DbUtil.java

package com.ahzysoft.export;

import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;


public class DbUtil {
    public static String[] getColumnName(ResultSetMetaData rsmd) throws SQLException {
        int count = rsmd.getColumnCount();
        String[] collumName = new String[count];
        for (int j = 0; j < count; j++) {
            collumName[j] = rsmd.getColumnLabel(j + 1).toLowerCase();
        }
        return collumName;
    }

    public static int[] getColumnType(ResultSetMetaData rsmd) throws SQLException {
        int colcount = rsmd.getColumnCount();
        int[] coltype = new int[colcount];    
        for (int i = 1; i <= colcount; i++) {
            int columnType=rsmd.getColumnType(i);
            switch (columnType) {            
            case Types.DECIMAL:
            case Types.INTEGER:
            case Types.NUMERIC:                
                if (rsmd.getScale(i) == 0) {
                    coltype[i - 1] = Type.INTEGER;
                } else {
                    coltype[i - 1] = Type.DOUBLE;
                }
                break;
            case Types.DOUBLE:
                coltype[i - 1] = Type.DOUBLE;
                break;
            case Types.CHAR:
            case Types.LONGVARCHAR:
            case Types.VARCHAR:
                coltype[i - 1] = Type.STRING;
                break;
            case Types.TIMESTAMP:
            case Types.DATE:
                coltype[i - 1] = Type.DATETIME;
                break;
            }
        }
        return coltype;
    }
}

IbatisUtil.java

package com.ahzysoft.export;

import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.ResultSet;


import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import com.ibatis.sqlmap.client.SqlMapSession;

public class IbatisUtil {
    private static SqlMapClient sqlMapClient;


    static {
        InputStreamReader reader = null;
        try {
            reader = new InputStreamReader(IbatisUtil.class
                    .getResourceAsStream("/SqlMapConfig.xml"));
            sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (Exception e) {
            }
        }
    }

    public static SqlMapSession getSqlMapSession() {
        return sqlMapClient.openSession();
    }

    public static void main(String[] args) {
        try {
            SqlMapSession session=IbatisUtil.getSqlMapSession();
            Connection conn=session.getDataSource().getConnection();
            ResultSet rs=conn.createStatement().executeQuery("select sysdate from dual");
            rs.next();
            System.out.println(rs.getString(1));
//            SqlMapSession session=sqlMapClient.openSession();
//            session.startTransaction();
//            
//            SqlMapSession session2=sqlMapClient.openSession();
//            session2.close();
//            
//            session.endTransaction();
            session.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            //IbatisUtil.close();
        }
    }
}

table.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap 
PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-2.dtd">

<sqlMap namespace="table">
    <select id="selTablename" resultClass="Tables">
        <![CDATA[
            select table_name from user_tables
        ]]>
    </select>
    
    <select id="selViewname" resultClass="Tables">
        <![CDATA[
            select view_name,text from user_views
        ]]>
    </select>
    
    <select id="selObjectname" parameterClass="String"  resultClass="Tables">
        <![CDATA[
            select object_name from user_objects where object_type = ‘PROCEDURE‘
        ]]>
    </select>
    
    <select id="selObjecttextByname" parameterClass="String"  resultClass="Tables">
        <![CDATA[
            select text from user_source  where type=‘PROCEDURE‘ and name=#objectname# order by line 
        ]]>
    </select>
    
    <!-- 获取数据库创建语句DDL(表结构) -->
    <select id="selTableddl" parameterClass="Map"  resultClass="String">
        <![CDATA[
            Select Dbms_Metadata.Get_Ddl(‘TABLE‘, #table#) From Dual
        ]]>
    </select>
    
    <select id="selSequences" resultClass="Tables">
        <![CDATA[
            select * from user_sequences
        ]]>
    </select>
    
    
</sqlMap>

    

从oracle数据库导出数据(表结构,表数据,视图,存储过程,序列)