利用opencsv来生成sql文----操作excel或着csv的研究

有时我们需要把数据导入数据库中,可我们手上有,.xls或着csv格式的文档数据,再加上因为一些逻辑关糸不能直接把它们导入到数据库中,这时就可以用利用opencsv来读取csv文档然后组全成sql文,再导入数据库。

下面是我写的一个例子,其中有很多定制的东西,如果需要要他用,要进行相应的修改。这算是提供一个思路和对opencsv的一个简单应用。
这个例子组合成的sql文直接打到了控制台,可以修改一下生成相应的文件。


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import au.com.bytecode.opencsv.CSVReader;

public class CsvDemo {
public static final File tempFile = new File("./test1.csv");
public static int constantVale = 15300;

public static void main(String[] args) throws IOException {
createSqlPart1();
}

public static List<Object> createSql(String[] nextLine) {
List<Object> strList = new ArrayList<Object>();
List<String> propList = new ArrayList<String>();

StringBuffer sql = new StringBuffer();
sql = sql
.append("Insert into FOG.T_TAG_INFO(TAGID, TAGNAME_ZH, TAGNAME_EN,CAREA, CITY, TAGTYPEID, TAGLEVEL, CLICKNUM)Values(");
constantVale = constantVale + 1;
sql.append(constantVale);
if (nextLine != null) {
for (int i = 0; i < nextLine.length; i++) {
String[] prop;
if (i == nextLine.length - 1) {
prop = nextLine[i].split("-");
} else {
prop = null;
}
if (prop != null) {
for (int j = 0; j < prop.length; j++) {
StringBuffer sqlprop = new StringBuffer();
sqlprop = sqlprop.append("INSERT INTO FOG.T_TAG_PROP (TAGID, PROP) VALUES (");
sqlprop.append(constantVale);
sqlprop.append(",");
sqlprop.append("'" + prop[j] + "'");
sqlprop.append(");");
propList.add(sqlprop.toString());
}
}
if (nextLine[i] != null && !nextLine[i].trim().equals("") && !(i == nextLine.length - 1)) {
sql.append(",");
sql.append("'" + nextLine[i].replaceAll("'", "''") + "'");
}

}
sql.append(",10,1,0);");
strList.add(sql.toString());
strList.add(propList);
}
return strList;
}

public static void createSqlPart1() throws IOException {
CSVReader reader = new CSVReader(new InputStreamReader(new FileInputStream(tempFile), "gb2312"));

String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
List<Object> list = createSql(nextLine);
System.out.println(list.get(0));
}
reader.close();
}

public static void createSqlPart2() throws IOException {
CSVReader reader = new CSVReader(new InputStreamReader(new FileInputStream(tempFile), "gb2312"));

String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
List<Object> list = createSql(nextLine);
List<Object> listProp = (List<Object>) list.get(1);
for (Object prop : listProp) {
System.out.println((String) prop);
}
}
reader.close();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值