【问题标题】:How to map the csv files Header names to the db Table while importing the data to db将数据导入数据库时​​如何将 csv 文件标题名称映射到数据库表
【发布时间】:2013-09-16 12:03:21
【问题描述】:

我已经编写了程序。如何将第一列映射到“Slno”,将第二列映射到“COM_BUS”。因为,csv 文件不包含与表一样的正确标题。 示例:
CSV 文件头有“sln”“C_BUS”

表“Business”的列有“SLNO”“COMBUS”。

我的问题是在将数据导入 db2 表时不应关注 csv 文件标题。请帮忙。

私有静态最终

String SQL_INSERT = "INSERT INTO OPTYMGT.${table}(${keys}, RUN_TS)   
                       VALUES(${values}, current_timestamp)";

private static final String TABLE_REGEX = "\\$\\{table\\}";
private static final String KEYS_REGEX = "\\$\\{keys\\}";
private static final String VALUES_REGEX = "\\$\\{values\\}";

private char seprator= ',';




public boolean loadCSV(Connection connection,String csvFile, String tableName) throws Exception {
    boolean  result = true;
    CSVReader csvReader = null;
    if(connection == null) {
        throw new Exception("Not a valid connection.");
    }
    try {

        csvReader = new CSVReader(new FileReader(csvFile), this.seprator);
        //System.out.println("csvReader" +csvReader);

    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception("Error occured while executing file. "
                + e.getMessage());
    }

    String[] headerRow = csvReader.readNext();

    //System.out.println("headerRow" +headerRow);

    if (null == headerRow) {
        throw new FileNotFoundException(
                "No columns defined in given CSV file." +
                "Please check the CSV file format.");
    }

    String questionmarks = StringUtils.repeat("?,", headerRow.length);
    questionmarks = (String) questionmarks.subSequence(0, questionmarks.length() - 1);
    String query = SQL_INSERT.replaceFirst(TABLE_REGEX, tableName);
    query = query.replaceFirst(KEYS_REGEX, StringUtils.join(headerRow, ","));
    query = query.replaceFirst(VALUES_REGEX, questionmarks);

    //System.out.println("Query: " + query);

/*  SimpleDateFormat cDate = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
    Date now = new Date();
    String ccDate = cDate.format(now);
    System.out.println("ccdate" +ccDate);*/

    String[] nextLine;
    Connection con = null;
    PreparedStatement ps = null;

【问题讨论】:

  • 那么,你是说这个程序从 CSV 的第一行读取列名,但是你想忽略第一行并使用不同的列名?如果是这样:您预先知道列名并且可以在 SQL 中对它们进行硬编码,还是想查看数据库并在运行时找出列名?
  • 您尝试重写IMPORTLOAD 实用程序是否有原因?

标签: java csv


【解决方案1】:

我遇到了类似的情况,解决方法是使用 Java 属性包创建一个将 bean 变量映射到标头的配置文件。我使用opencsv 将 csv 映射到 Java 对象。但是,在此之前我检查文件是否有标题,如果没有,我将标题写入 csv 的第一行。由于我使用opencsv,因此我注释了类变量以定义映射。希望对你有帮助。

假期后我很高兴分享代码

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-30
    • 2012-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    相关资源
    最近更新 更多