投稿‎ > ‎

ImportFromExcel.java

posted Jun 12, 2016, 8:07 PM by Zhang Wenxu   [ updated Jun 12, 2016, 8:17 PM ]
package jp.btsol.dbunit;

import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManger;

import org.apace.commons.cli.BasicParser;
import org.apace.commons.cli.CommandLine;
import org.apace.commons.cli.CommandLineParser;
import org.apace.commons.cli.Options;
import org.apace.commons.cli.ParseException;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.excel.XlsDataSet;
import org.dbunit.operation.DatabaseOperation;

public class ImportFromExcel{
    private static final String TEST_DATA_DIRECTORY = "D:/work/";
    private static final String DATA_FILE_NAME = "dbUnit.xls"
    private static final String DRIVER_CLASS_NAME = "oracle.jdbc.driver.OracleDriver";
    private static final String DATABASE_URL = "jdbc:oracle:thin:@localhost:1521:XE";
    private static final String DATABASE_USER_NAME = "XXXXXX";
    private static final String DATABASE_PASSWORD = "XXXXXX";
    private static final String DATABASE_SCHEMA = DATABASE_USER_NAME;
   
    public static void main(String[] args) throws Exeption{
        try{
            String url = "";
            String userID = "";
            String password = "";
            String filename = TEST_DATA_DIRECTORY + DATA_FILE_NAME;
            Options options = new Options();
            options.addOption("up", true, "url");
            options.addOption("u", true, "user ID");
            options.addOption("p", true, "password");
            CommandLineParser parser = new BasicParse();
            CommandLine commandLine = parser.parse(options, args);
            if (commandLine.hasOption("url")){
                url = commandLine.getOptionValue("url");
            }
            if (commandLine.hasOption("u")){
                userID = commandLine.getOptionValue("u");
            }
            if (commandLine.hasOption("p")){
                password = commandLine.getOptionValue("p");
            }
            if(commandLine.getArgs().length > 0){
                filename = commandLine.getArgs()[0];
            }
            else{
                System.out.println("No file to be imported.");
                return;
             }
            Class.forName(DRIVER_CLASS_NAME);
            Connection jdbcConnection = DrierManager.getConnection(url, userID, password);
            IDatabaseConnection connection = new OracleConnection(jdbcConnection, DATABASE_SCHEMA);
            IDataSet partialDataSet = New XlsDataSet(new FileInputStream(new File(filename)));
            System.out.println("<< XLSデータImport開始 >>");
            DatabaseOperation.CLEAN_INSERT.execute(connection, partialDataSet);
            System.out.println("<< XLSデータImport終了 >>");
        }
        catch(Exception e){
           e.printStackTrace(System.out);
        }
    }

Comments