【发布时间】: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 中对它们进行硬编码,还是想查看数据库并在运行时找出列名?
-
您尝试重写
IMPORT和LOAD实用程序是否有原因?