【问题标题】:data being insterted into DB multiple times when scanning file for marked words扫描文件以查找标记单词时多次将数据插入数据库
【发布时间】:2016-02-05 01:54:57
【问题描述】:

我有一个应用程序可以扫描文本文件中的某些单词,如果找到这些单词,则更新数据库表。我逐行扫描文件中的某些单词,例如这样

public void scanFile(File toBeScanned) {
    try {

        InputStream instream = new FileInputStream(toBeScanned);

        if (instream != null) {

            InputStreamReader inputreader = new InputStreamReader(instream);
            BufferedReader buffreader = new BufferedReader(inputreader);
            String line;


            // read every line of the file into the line-variable, 1 line at the time
            do {
                line = buffreader.readLine();
                if (line.contains("word1"))
                    doInsert("word1", ourJavaTimestampObject , id ,"Test_Child");
                if (line.contains("word2"))
                    doInsert("word2", ourJavaTimestampObject, id ,"Test_Child");                    
                if (line.contains("word3"))
                    doInsert("word3", ourJavaTimestampObject, id, "Test_Child");

            } while (line != null);

我的程序成功地提取了这些词,但正在用它们多次填充数据库。例如。 word1,word2,word2 被发送到 DB,第二次点击时 DB 有 word1,word2,word2,word1,word2,word2 等等。

我通过单击按钮调用 scanFile 方法,并且任何时候发生的单词都会重新输入到数据库中。

我希望我的程序只插入一个单词的每个实例一次。所以在文件被逐行读取之后,最好的做法可能是清空文件?或者我的循环可能需要不同的方法

这里也是插入方法

public void doInsert(String word, java.sql.Timestamp ourJavaTimestampObject, int userID , String child) {
        try {

            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection(url, user, pass);
            Statement st = con.createStatement();
            st.executeUpdate("\n" +
                    "INSERT IGNORE INTO FLAGS (FLAG_WORD, FLAG_DATE, FLAG_USER, FLAG_CHILD)\n" +
                    "VALUES  ('" + word + "' , '" + ourJavaTimestampObject + "' , '" + userID + "','" + Register.child + "')");


            con.close();        

        } catch (SQLException ex) {

        } catch (ClassNotFoundException e) {

        }

    }// end method insert

非常感谢任何建议,我已经坚持了好几个小时了。

【问题讨论】:

  • 你使用了哪种方法?

标签: java mysql file loops bufferedreader


【解决方案1】:

我从问题中了解到的是,您不想再次从同一个文件中读取内容。

一种方法是将文件名保存在数据库中(假设文件名是唯一的)并在插入前检查数据库中的唯一文件名。

第二种方法是按照您的建议清空文件。或者,您可以将诸如“已读”之类的标题(在第 1 行)附加到文件中,这将作为文件已被您读取的指示符。

【讨论】:

    【解决方案2】:

    INSERT IGNORE 与 PRIMARY KEY 配合使用,因此请确保将 FLAG_WORD 列设置为主键,以免单词重复。

    【讨论】:

      猜你喜欢
      • 2015-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多