從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 = min_value;
    }

    public String getMax_value() {
        return max_value;
    }

    public void setMax_value(String max_value) {
        this.max_value = 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>

    


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM