2012-06-24 59 views
0
import java.io.File; 
import java.io.IOException; 
import java.sql.*; 
import java.util.List; 

import org.apache.commons.io.FileUtils; 

public class DBWriter { 

    private static String user = "root"; 
    private static String pw = ""; 
    private static String dbUrl = "jdbc:mysql://127.0.0.1/NLD"; 
    private static String dbClass = "com.mysql.jdbc.Driver"; 
    // public static String scraped_commentsInsert = "INSERT INTO scraped_comments (id, movie_title,user_comments) VALUES (?,?,?)"; 
    Connection con; 
    Statement st=con.createStatement(); 
    private PreparedStatement multiInsert; 

    DBWriter() throws IOException, SQLException{ 
     String Title; 
     String Comment; 
     try { 
      Class.forName(dbClass); 
      con = DriverManager.getConnection(dbUrl, user, pw); 
      con.setAutoCommit(false); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     List lines = FileUtils.readLines(new File("/Users/samualdoku/Desktop/Twitter/scraped.txt"), "UTF-8"); 
     for (Object line : lines) { 

      if (String.valueOf(line).startsWith("title : ") || (String.valueOf(line).startsWith("comment : "))) 
      { 
       Title = line.toString(); 
       System.out.println(Title); 

       Comment = line.toString(); 
       System.out.println(Comment); 
       int k=st.executeUpdate("INSERT INTO scraped_comments (id, movie_title,user_comments) values("+id+",'"+Title+"','"+Comment+"')"); 
      } 
     } 
    } 
} 

這是我試圖在數據庫中存儲的文件。我想獲得存儲的標題和評論。我確實懂得它,但它只存儲第一行。 請幫忙,數據庫不太好。如何將這樣的文件插入到MySQL數據庫中

title : The Descent Part 2 comment : badbaz83 : No it wasn't as good as the first one, but a hell of a lot better than I first feared. Worth a watch, but don't expect it to stand up to the first film. 

title : Supernatural comment : MissAyla : I loved this episode. :) I'm thoroughly enjoying the new style, just like the original episodes. 

title : Soccer Mom comment : chantellel93 : it's only 10 min so if u smoke 1 its worth the laugh 2/5. xx 
+0

它遍歷所有行嗎?是否拋出異常? –

+0

解析一個普通的txt文件將是一個痛苦的* ss ...你有沒有考慮過使用XML文件? – tftd

+0

你在哪裏設置'id'?如果'id'是主鍵,它必須是唯一的。如果你想自動增加'id',你不需要在你的插入語句中提供它 – KCD

回答

1

首先需要line分成TitleComment和分配id。試試這個(注意區分大小寫):

String s = line.toString(); 
Title = s.substring(8, s.indexOf("comment :")).trim(); 
Comment = s.substring(s.indexOf("comment :") + 10, s.length()).trim(); 

然後讓我們知道你在哪裏。

我假設你正在嘗試做這個數據庫插入(SQLFiddle)。 要自動分配一個ID你可以設置ID爲你的auto_increment主鍵(按照我的例子)。您可以使用executeUpdate(String sql, int autoGeneratedKeys)

當您提供有關問題的更多詳細信息時,我會嘗試更新我的答案。

相關問題