Lucene为数据库建立索引

import java.sql.DriverManager; import java.sql.ResultSet; import java.util.Date; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexWriter; import org.wltea.analyzer.lucene.IKAnalyzer; import com.mysql.jdbc.Connection; import com.mysql.jdbc.Statement; public class CreateIndexForSQL { public static String INDEX_STORE_PATH = "D:/indexsql"; @SuppressWarnings("deprecation") public static void main(String[] args) { long start = new Date().getTime(); String driver = "com.mysql.jdbc.Driver"; String url = "jdbc:MySQL://127.0.0.1:3306/search"; String user = "root"; String password = "root"; Connection conn = null; Statement stmt = null; ResultSet rs = null; try { // 1.加载数据库的驱动程序 Class.forName(driver); // 2.提供数据库连接的URL String SQL = "SELECT * FROM search.news"; // 3.通过DriverManager获得数据库的一个连接对象 conn = (Connection) DriverManager .getConnection(url, user, password); // 4.创建Statement(SQL执行环境) stmt = (Statement) conn.createStatement(); // 5.执行SQL语句 rs = stmt.executeQuery(SQL); // 6.创建索引 IndexWriter writer = new IndexWriter(INDEX_STORE_PATH, new IKAnalyzer(), true); while (rs.next()) { Document doc = new Document(); doc.add(new Field("title", rs.getString("title"), Field.Store.YES, Field.Index.TOKENIZED)); doc.add(new Field("contents", rs.getString("contents"), Field.Store.YES, Field.Index.TOKENIZED)); writer.addDocument(doc); } // 7.关闭索引 writer.optimize(); writer.close(); } catch (Exception e) { e.printStackTrace(); } finally { // 7.关闭JDBC的资源 if (rs != null) try { rs.close(); } catch (Exception e) { } if (stmt != null) try { stmt.close(); } catch (Exception e) { } if (conn != null) try { conn.close(); } catch (Exception e) { } } long end = new Date().getTime(); System.out.println("创建索引成功"); System.out.println("共耗时" + (end - start) + "ms"); } }

你可能感兴趣的:(sql,exception,数据库,String,jdbc,Lucene)