1. 程式人生 > >ETL-kettle通過java程式碼傳遞引數,呼叫job呼叫轉換

ETL-kettle通過java程式碼傳遞引數,呼叫job呼叫轉換

定義變數,以表輸入為例,定義變數名稱為${變數名},這裡用test為變數名。並且勾選sql語句變數

package demo;

import org.pentaho.di.core.KettleEnvironment;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.job.Job;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.repository.RepositoryDirectoryInterface;
import org.pentaho.di.repository.kdr.KettleDatabaseRepository;
import org.pentaho.di.repository.kdr.KettleDatabaseRepositoryMeta;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;

public class KettleTest {
    public static void runWithDb() throws Exception {
        KettleEnvironment.init();
        //建立DB資源庫
        KettleDatabaseRepository repository=new KettleDatabaseRepository();
        DatabaseMeta databaseMeta=new DatabaseMeta("kettle","mysql","jdbc","localhost","kettle_repository","3306","root","root");
        //選擇資源庫
        KettleDatabaseRepositoryMeta kettleDatabaseRepositoryMeta=new KettleDatabaseRepositoryMeta("kettle","kettle","Transformation description",databaseMeta);
        repository.init(kettleDatabaseRepositoryMeta);
        //連線資源庫
        repository.connect("admin","admin");
        RepositoryDirectoryInterface directoryInterface=repository.loadRepositoryDirectoryTree();
        //選擇轉換
//        TransMeta transMeta=repository.loadTransformation("測試隨機數",directoryInterface,null,true,null);
//        Trans trans=new Trans(transMeta);
//        trans.execute(null);
//        trans.waitUntilFinished();//等待直到資料結束
//        if(trans.getErrors()>0){
//            System.out.println("transformation error");
//        }else{
//            System.out.println("transformation successfully");
//        }
        // 選擇job 這裡採用job
        JobMeta jobMeta = repository.loadJob("random", directoryInterface, null, null);
        Job job = new Job(repository, jobMeta);
        // 向Job 指令碼傳遞引數,指令碼中獲取引數值:${引數名}
        // job.setVariable(paraname, paravalue);
        job.setVariable("test", "jing_vehicle_result_mapping");    //變數名稱key-value
        job.start();
        job.waitUntilFinished();
        if (job.getErrors() > 0) {
            throw new Exception(
                    "There are errors during job exception!(執行job發生異常)");
        }
    }

    public static void main(String[] args) throws Exception {
        KettleTest.runWithDb();
    }

}

 

左上角編輯中,可以檢視變數名稱

然後執行程式碼。可以看到響應的檔案就已經寫入的資料。

程式碼中需要引用相應的jar包

jar包在kettle工具檔案下一個叫lib的資料夾中可以查詢獲得。