我写了这个程序。如何将第一列映射到“Slno”,第二列映射到“COM_BUS”。因为,csv文件不包含与表格一样的正确标题。
例如:
CSV文件头有“sln”“C_BUS”
表“商家”栏中有“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;
答案 0 :(得分:0)
我遇到了类似的情况,解决方法是使用Java属性包创建一个将bean变量映射到头文件的配置文件。我使用opencsv
将csv映射到Java对象。但是,在此之前我检查文件是否有标题,如果没有,我将标题写入csv的第一行。由于我使用opencsv
,因此我对类变量进行了注释以定义映射。我希望它有所帮助。
我很高兴在假期后分享代码