日期:2014-05-16 浏览次数:20480 次
/** * */ package net.tuolian.product.utils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Date; import jeasy.analysis.MMAnalyzer; /** * @author sean * * @since 2009/04/17 * 1. 读取包含专业词库的txt文件 * 2. 根据中文分词组件进行切分 * 3. split方法处理,返回字符串数组 * 4. 写出到txt文件输出 * 5. 使用sql批量更新方式插入数据库 */ public class JdbcBatchUpdate { static String sql = "insert into test04 values (?,?)"; Connection conn = null; PreparedStatement pstmt = null; /** * @param args * @throws SQLException * @throws ClassNotFoundException * @throws IOException * @throws IllegalAccessException * @throws InstantiationException */ public static void main(String[] args) throws SQLException, ClassNotFoundException, IOException, InstantiationException, IllegalAccessException { // TODO Auto-generated method stub JdbcBatchUpdate update = new JdbcBatchUpdate(); update.init(); //读取txt文件 BufferedReader reader = new BufferedReader(new FileReader("keywordsource//output.txt")); //打开输出文件 BufferedWriter writer = new BufferedWriter(new FileWriter("newoutput.txt")); String str = null; StringBuffer sb = new StringBuffer(); while((str= reader.readLine())!=null){ sb.append(str + " "); } //中文分词插件,JEAnalysis, 根据" "空格,将sb的字符串进行分词 MMAnalyzer analyzer = new MMAnalyzer(); String msg = analyzer.segment(sb.toString(), " "); //将字符串更加空格进行分割,返回字符串数组 String[] terms = msg.toString().split(" "); //输出到txt文件 for(int i=0; i<terms.length;i++){ System.out.println(i + terms[i]); writer.write(terms[i] + "\r\n"); } writer.flush(); writer.close(); //执行mysql批量更新到数据库 update.batchUpdate(terms); } /** * 数据库连接初始化 * 1. 加载mysql jar包 * 2. 获得getConnection * 3. 获得PreparedStatement * @throws SQLException * @throws ClassNotFoundException */ public void init() throws SQLException, ClassNotFoundException{ Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/db_advertisement", "root", "root"); conn.setAutoCommit(false); pstmt = (PreparedStatement) conn .prepareStatement(sql); System.out.println(new Date()); } /** * 批量更新 * 先加入批量, pstm.addBatch() * 然后executeBatch(), 批量更新 * conmit(), 更新 * @param terms * @throws SQLException */ public void batchUpdate(String[] terms) throws SQLException{ for (int i = 0; i < terms.length -1; i++) { //此处注意setInt(1, i), 字段名称和栏目数必须匹配 pstmt.setInt(1, i); pstmt.setString(2, terms[i]); pstmt.addBatch(); System.out.println(i); } //增加到批量工作任务中 pstmt.executeBatch(); System.out.println(new Date()); //提交执行 conn.commit(); pstmt.close(); conn.close(); } }