- 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<String> 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);
- }
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/0203201511825.html
来源: http://www.codesnippet.cn/detail/0203201511825.html