java - 扫描文件中的标记单词时,数据被多次插入数据库

标签 java mysql file loops bufferedreader

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

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 被发送到数据库,第二次点击数据库有 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

非常感谢任何建议,我已经在这个问题上坚持了几个小时了。

最佳答案

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

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

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

关于java - 扫描文件中的标记单词时,数据被多次插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33524096/

相关文章:

java - 配置 Web 应用程序以在 JBoss 7 中显示索引页面(使用 Maven)

php - MySQL Left JOIN Group_concat 性能问题

创建具有定义大小的文件

mysql - WAMP 的 MySQL 数据库文件位于何处?

file - 您如何管理和组织您的文件? (脚本、repos、下载、pdf 等)

java - 我怎样才能返回我的主类?

java - Spring MVC : Unable to access HTML page via InternalResourceViewResolver

java - 如何提取文件 jre-9/lib/modules?

mysql - 需要 mySQL 函数来打乱列中的文本

Mysql存储过程