package com.nd.jdbc;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;
import org.apache.commons.io.FileUtils;
public class ImportMysqlTest {
/**
* @param args
*/
public static void main(String[] args) {
ImportMysqlTest sBase = new ImportMysqlTest();
sBase.ImportMysql("e://sina/out/sina_search.txt", "表名");
}
public void ImportMysql(String filepath, String tableName) {
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = BaseDao.getConn();
conn.setAutoCommit(false);
pstmt = conn
.prepareStatement("load data local infile '' "
+ "into table " + tableName
+ " fields terminated by '@|@'");
StringBuilder sb = new StringBuilder();
List str = FileUtils.readLines(new File(filepath), "UTF-8");
for (int i = 0; i < str.size(); i++) {
sb.append(str.get(i) + "\\n");
if (i % 500 == 0) {
InputStream is = new ByteArrayInputStream(sb.toString()
.getBytes("UTF-8"));
((com.mysql.jdbc.Statement) pstmt)
.setLocalInfileInputStream(is);
pstmt.execute();
conn.commit();
sb.setLength(0);
}
}
InputStream is = new ByteArrayInputStream(sb.toString().getBytes(
"UTF-8"));
((com.mysql.jdbc.Statement) pstmt).setLocalInfileInputStream(is);
pstmt.execute();
conn.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
BaseDao.closeAll(pstmt, conn);
}
}
}