데이터 베이스 MySQL 튜토리얼 kettle api 执行转换

kettle api 执行转换

Jun 07, 2016 pm 03:10 PM
api import 구현하다 전환하다

import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.util.Date; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.LogWriter; import be.ibridge.kettle.core.NotePadMeta; import b


import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;

import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.LogWriter;
import be.ibridge.kettle.core.NotePadMeta;
import be.ibridge.kettle.core.database.Database;
import be.ibridge.kettle.core.database.DatabaseMeta;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.trans.StepLoader;
import be.ibridge.kettle.trans.Trans;
import be.ibridge.kettle.trans.TransHopMeta;
import be.ibridge.kettle.trans.TransMeta;
import be.ibridge.kettle.trans.step.StepMeta;
import be.ibridge.kettle.trans.step.StepMetaInterface;
import be.ibridge.kettle.trans.step.selectvalues.SelectValuesMeta;
import be.ibridge.kettle.trans.step.tableinput.TableInputMeta;
import be.ibridge.kettle.trans.step.tableoutput.TableOutputMeta;

/**
 *
 *

Title:
 * 本文描述了以下操作:

1)           建立一个新的转换(transformation)

2)           把转换(transformation)存储为XML文件

3)           生成需要在目标表运行的SQL语句

4)           执行转换(transformation)

5)           删除目标表,可以使测试程序可以反复执行(这一点可根据需要修改)。


 *

Description: TODO 类的功能描述


 *

Copyright: Copyright (c) 2003



 * @author 洪亮
 * @version 1.0
 *

------------------------------------------------------------


 *

修改历史


 *

  序号    日期       时间        修 改 人    修 改 原 因


 *

   1    2006-9-20   下午05:59:06     洪亮       创建 


 *
 */

public class TransBuilderME
{
    public static final String[] databasesXML = {
        "" +
        "" +
            "target" +
            "192.168.169.220" +
            "ORACLE" +
            "Native" +
            "NMSDB" +
            "1521" +
            "UCP" +
            "UCP" +
          "
",
         
          "" +
          "" +
              "source" +
              "192.168.169.220" +
              "ORACLE" +
              "Native" +
              "NMSDB" +
              "1521" +
              "UCP" +
              "UCP" +
            "

    };

    /**
     * Creates a new Transformation using input parameters such as the tablename to read from.
     * @param transformationName The name of the transformation
     * @param sourceDatabaseName The name of the database to read from
     * @param sourceTableName The name of the table to read from
     * @param sourceFields The field names we want to read from the source table
     * @param targetDatabaseName The name of the target database
     * @param targetTableName The name of the target table we want to write to
     * @param targetFields The names of the fields in the target table (same number of fields as sourceFields)
     * @return A new transformation
     * @throws KettleException In the rare case something goes wrong
     */
    public static final TransMeta buildCopyTable(String transformationName, String sourceDatabaseName, String sourceTableName, String[] sourceFields, String targetDatabaseName, String targetTableName, String[] targetFields) throws KettleException
    {
        LogWriter log = LogWriter.getInstance();
       
        try
        {
            //
            // Create a new transformation...
            //传输元信息
            TransMeta transMeta = new TransMeta();
            transMeta.setName(transformationName);//传输名称
           
            // Add the database connections
            for (int i=0;i            {
                DatabaseMeta databaseMeta = new DatabaseMeta(databasesXML[i]);//数据库元信息
                transMeta.addDatabase(databaseMeta);//传输元  中加入数据库元信息
            }
           
            DatabaseMeta sourceDBInfo = transMeta.findDatabase(sourceDatabaseName);//查找源数据库元信息
            DatabaseMeta targetDBInfo = transMeta.findDatabase(targetDatabaseName);//查找目标数据库元信息

           
            //
            // Add a note
            //
            String note = "Reads information from table [" + sourceTableName+ "] on database [" + sourceDBInfo + "]" + Const.CR;
            note += "After that, it writes the information to table [" + targetTableName + "] on database [" + targetDBInfo + "]";
            NotePadMeta ni = new NotePadMeta(note, 150, 10, -1, -1);//注释信息
            transMeta.addNote(ni);

            //
            // create the source step...
            //
            String fromstepname = "read from [" + sourceTableName + "]";//from步骤名称
            TableInputMeta tii = new TableInputMeta();//表输入元数据信息
            tii.setDatabaseMeta(sourceDBInfo);//为表输入 指定 数据库
            String selectSQL = "SELECT "+Const.CR;//拼接查询sql语句
            for (int i=0;i            {
                if (i>0) selectSQL+=", "; else selectSQL+="  ";
                selectSQL+=sourceFields[i]+Const.CR;
            }
            selectSQL+="FROM "+sourceTableName;
            tii.setSQL(selectSQL);//设置查询sql语句

            StepLoader steploader = StepLoader.getInstance();//???

            String fromstepid = steploader.getStepPluginID(tii);
            //步骤元数据信息
            StepMeta fromstep = new StepMeta(log, fromstepid, fromstepname, (StepMetaInterface) tii);
            fromstep.setLocation(150, 100);
            fromstep.setDraw(true);
            fromstep.setDescription("Reads information from table [" + sourceTableName + "] on database [" + sourceDBInfo + "]");
            //传输中 添加步骤
            transMeta.addStep(fromstep);
            //
            // add logic to rename fields
            // Use metadata logic in SelectValues, use SelectValueInfo...
            //选择字段(重命名)
            SelectValuesMeta svi = new SelectValuesMeta();
            svi.allocate(0, 0, sourceFields.length);
            for (int i = 0; i             {
             //设置源字段和目标字段
                svi.getMetaName()[i] = sourceFields[i];
                svi.getMetaRename()[i] = targetFields[i];
            }

            String selstepname = "Rename field names";
            //获取步骤插件ID
            String selstepid = steploader.getStepPluginID(svi);
            //创建步骤元数据信息
            StepMeta selstep = new StepMeta(log, selstepid, selstepname, (StepMetaInterface) svi);
            selstep.setLocation(350, 100);
            selstep.setDraw(true);
            selstep.setDescription("Rename field names");
            //添加步骤
            transMeta.addStep(selstep);

            //传输连接元数据信息(连接from和select)
            TransHopMeta shi = new TransHopMeta(fromstep, selstep);
            transMeta.addTransHop(shi);//添加到传输元对象
            fromstep = selstep;//然后设置from步骤为select步骤

            //
            // Create the target step...
            //
            //
            // Add the TableOutputMeta step...
            //设置目标步骤名称
            String tostepname = "write to [" + targetTableName + "]";
            //表输出元对象
            TableOutputMeta toi = new TableOutputMeta();
            toi.setDatabase(targetDBInfo);//设置数据库
            toi.setTablename(targetTableName);//设置表名
            toi.setCommitSize(3000);//设置批量提交数
            toi.setTruncateTable(true);//是否清除原有数据

            //获取步骤ID
            String tostepid = steploader.getStepPluginID(toi);
            //创建to步骤
            StepMeta tostep = new StepMeta(log, tostepid, tostepname, (StepMetaInterface) toi);
            tostep.setLocation(550, 100);
            tostep.setDraw(true);
            tostep.setDescription("Write information to table [" + targetTableName + "] on database [" + targetDBInfo + "]");
            transMeta.addStep(tostep);//添加步骤

            //
            // Add a hop between the two steps...
            //
            //创建连接 from--to
            TransHopMeta hi = new TransHopMeta(fromstep, tostep);
            transMeta.addTransHop(hi);

            // OK, if we're still here: overwrite the current transformation...
            return transMeta;
        }
        catch (Exception e)
        {
            throw new KettleException("An unexpected error occurred creating the new transformation", e);
        }
    }

    /**
     * 1) create a new transformation
     * 2) save the transformation as XML file
     * 3) generate the SQL for the target table
     * 4) Execute the transformation
     * 5) drop the target table to make this program repeatable
     *
     * @param args
     */
    public static void main(String[] args) throws Exception
    {
        long start = new Date().getTime();
        // Init the logging...
        LogWriter log = LogWriter.getInstance("TransBuilder.log", true, LogWriter.LOG_LEVEL_DETAILED);
       
        // Load the Kettle steps & plugins
        StepLoader stloader = StepLoader.getInstance();
        if (!stloader.read())
        {
            log.logError("TransBuilder",  "Error loading Kettle steps & plugins... stopping now!");
            return;
        }
       
        // The parameters we want, optionally this can be
        String fileName = "./NewTrans.xml";
        String transformationName = "Test Transformation";
        String sourceDatabaseName = "source";
        String sourceTableName = "emp_collect";
        String sourceFields[] = {
          "empno",      
          "ename",      
          "job",        
          "mgr",        
          "comm",       
          "sal",        
          "deptno",     
          "birthday"   
 
            };

        String targetDatabaseName = "target";
        String targetTableName = "emp_kettle01";
        String targetFields[] = {
          "empno01",      
          "ename01",      
          "job01",        
          "mgr01",        
          "comm",       
          "sal",        
          "deptno",     
          "birthday"
            };

       
        // Generate the transformation.
        //创建转换元对象
        TransMeta transMeta = TransBuilderME.buildCopyTable(
                transformationName,
                sourceDatabaseName,
                sourceTableName,
                sourceFields,
                targetDatabaseName,
                targetTableName,
                targetFields
                );
//        transMeta = new  TransMeta();
        // Save it as a file:
        //传输元对象 中获得XML,并输出
        String xml = transMeta.getXML();
        DataOutputStream dos = new DataOutputStream(new FileOutputStream(new File(fileName)));
        dos.write(xml.getBytes("UTF-8"));
        dos.close();
        System.out.println("Saved transformation to file: "+fileName);

        // OK, What's the SQL we need to execute to generate the target table?
        //获得sql语句,创建表语句
        String sql = transMeta.getSQLStatementsString();

        // Execute the SQL on the target table:
        //创建表
        Database targetDatabase = new Database(transMeta.findDatabase(targetDatabaseName));
        targetDatabase.connect();//连接数据库
        targetDatabase.execStatements(sql);//执行sql
       
        // Now execute the transformation...
        //执行传输任务
        Trans trans = new Trans(log, transMeta);
        trans.execute(null);
        trans.waitUntilFinished();//等待执行完毕
       
        // For testing/repeatability, we drop the target table again
//        targetDatabase.execStatement("drop table "+targetTableName);
        targetDatabase.disconnect();//断开数据库连接
       
        long end = new Date().getTime();
        System.out.println("运行时间:" + (end - start) / 1000 + "秒");
        long min = (end - start) / 1000 / 60;
        long second = (end - start) / 1000 % 60;
        System.out.println("运行时间:" + min + "分钟" + second + "秒");
    }


}
 

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

전각 영문자를 반각 형태로 변환하는 실용적인 팁 전각 영문자를 반각 형태로 변환하는 실용적인 팁 Mar 26, 2024 am 09:54 AM

전각 영문자를 반각 형태로 변환하는 실용팁 현대생활에서 우리는 영문자를 자주 접하게 되고, 컴퓨터나 휴대폰, 기타 기기를 사용할 때 영문자를 입력해야 하는 경우가 많습니다. 그러나 때로는 영어의 전각 문자를 접하게 되므로 반각 형식을 사용해야 합니다. 그렇다면 전각 영문자를 반각 형태로 변환하는 방법은 무엇일까요? 다음은 몇 가지 실용적인 팁입니다. 먼저, 전각 영문자 및 ​​숫자는 입력방법에서 전각 위치를 차지하는 문자를 말하며, 반각 영문자 및 ​​숫자는 전각 위치를 차지한다.

PHP 월을 영어 월로 변환하는 구현 방법에 대한 자세한 설명 PHP 월을 영어 월로 변환하는 구현 방법에 대한 자세한 설명 Mar 21, 2024 pm 06:45 PM

이 기사에서는 PHP의 월을 영어 월로 변환하는 방법을 자세히 소개하고 구체적인 코드 예제를 제공합니다. PHP 개발 시 디지털 월을 영어 월로 변환해야 하는 경우가 있는데, 이는 일부 날짜 처리 또는 데이터 표시 시나리오에서 매우 실용적입니다. 구현 원칙, 구체적인 코드 예시, 주의사항은 아래에서 자세히 설명하겠습니다. 1. 구현 원리 PHP에서는 DateTime 클래스와 형식 메소드를 사용하여 디지털 월을 영어 월로 변환할 수 있습니다. 날짜

qq 음악을 mp3 형식으로 변환하는 방법 휴대폰에서 qq 음악을 mp3 형식으로 변환 qq 음악을 mp3 형식으로 변환하는 방법 휴대폰에서 qq 음악을 mp3 형식으로 변환 Mar 21, 2024 pm 01:21 PM

QQ Music을 사용하면 누구나 영화를 감상하고 지루함을 해소할 수 있습니다. 이 소프트웨어를 사용하면 누구나 쉽게 들을 수 있는 고품질 노래를 다운로드할 수 있습니다. 다음에 들을 때는 인터넷 연결이 필요하지 않습니다. 여기에서 다운로드한 노래는 MP3 형식이 아니며 다른 플랫폼에서 사용할 수 없습니다. 따라서 해당 노래를 다시 들을 수 없습니다. , 많은 친구들이 노래를 MP3 형식으로 변환하고 싶어합니다. 여기서 편집자는 모든 사람이 사용할 수 있도록 방법을 제공한다고 설명합니다. 1. 컴퓨터에서 QQ Music을 열고 오른쪽 상단의 [메인 메뉴] 버튼을 클릭한 후 [오디오 트랜스코딩]을 클릭하고 [노래 추가] 옵션을 선택한 후 변환해야 하는 노래를 추가합니다. 노래를 클릭하여 [mp3]로 변환을 선택하세요.

전각 영문자를 반각 문자로 변환하는 방법 전각 영문자를 반각 문자로 변환하는 방법 Mar 25, 2024 pm 02:45 PM

전각 영문자를 반각자로 변환하는 방법 일상생활이나 직장에서 컴퓨터 비밀번호를 입력하거나 문서를 편집하거나 작업을 할 때 전각 영문자를 반각자로 변환해야 하는 상황에 직면할 때가 있습니다. 레이아웃 디자인. 영문자와 숫자는 한자와 폭이 같은 문자를 의미하고, 영문자는 한자와 폭이 좁은 문자를 의미합니다. 실제 작업에서는 텍스트와 숫자를 보다 편리하게 처리할 수 있도록 영문 전각을 반각 문자로 변환하는 몇 가지 간단한 방법을 익혀야 합니다. 1. 영문자 전각 및 영문자 반각

PHP 튜토리얼: int 유형을 문자열로 변환하는 방법 PHP 튜토리얼: int 유형을 문자열로 변환하는 방법 Mar 27, 2024 pm 06:03 PM

PHP 튜토리얼: Int 유형을 문자열로 변환하는 방법 PHP에서는 정수 데이터를 문자열로 변환하는 것이 일반적인 작업입니다. 이 튜토리얼에서는 특정 코드 예제를 제공하면서 PHP의 내장 함수를 사용하여 int 유형을 문자열로 변환하는 방법을 소개합니다. 캐스트 사용: PHP에서는 캐스트를 사용하여 정수 데이터를 문자열로 변환할 수 있습니다. 이 방법은 매우 간단합니다. 정수 데이터 앞에 (문자열)을 추가하면 문자열로 변환됩니다. 아래는 간단한 샘플 코드입니다.

PHP의 ASCII 값 변환에 대해 빠르게 알아보기 PHP의 ASCII 값 변환에 대해 빠르게 알아보기 Mar 28, 2024 pm 06:42 PM

PHP의 ASCII 값 변환은 프로그래밍에서 자주 발생하는 문제입니다. ASCII(American Standard Code for Information Interchange)는 문자를 숫자로 변환하는 표준 인코딩 시스템입니다. PHP에서는 ASCII 코드를 통해 문자와 숫자를 변환해야 하는 경우가 많습니다. 이 기사에서는 PHP에서 ASCII 값을 변환하는 방법을 소개하고 구체적인 코드 예제를 제공합니다. 1. 캐릭터 변경

Oracle API 사용 가이드: 데이터 인터페이스 기술 탐색 Oracle API 사용 가이드: 데이터 인터페이스 기술 탐색 Mar 07, 2024 am 11:12 AM

Oracle은 세계적으로 유명한 데이터베이스 관리 시스템 제공업체이며, Oracle의 API(응용 프로그래밍 인터페이스)는 개발자가 Oracle 데이터베이스와 쉽게 상호 작용하고 통합하는 데 도움이 되는 강력한 도구입니다. 이 기사에서는 Oracle API 사용 가이드를 자세히 살펴보고 독자들에게 개발 프로세스 중에 데이터 인터페이스 기술을 활용하는 방법을 보여주고 구체적인 코드 예제를 제공합니다. 1.오라클

exe에서 php로: 기능 확장을 위한 효과적인 전략 exe에서 php로: 기능 확장을 위한 효과적인 전략 Mar 04, 2024 pm 09:36 PM

EXE에서 PHP로: 기능 확장을 위한 효과적인 전략 인터넷의 발전과 함께 더 많은 사용자 액세스와 더 편리한 작업을 위해 점점 더 많은 응용 프로그램이 웹으로 마이그레이션되기 시작했습니다. 이 과정에서 원래 EXE(실행 파일)로 실행되는 기능을 PHP 스크립트로 변환하려는 요구도 점차 늘어나고 있다. 이 기사에서는 기능 확장을 위해 EXE를 PHP로 변환하는 방법에 대해 설명하고 구체적인 코드 예제를 제공합니다. EXE를 PHP 크로스 플랫폼으로 변환하는 이유: PHP는 크로스 플랫폼 언어입니다.

See all articles