mercredi 4 novembre 2015

data being insterted into DB multiple times when scanning file for marked words

I have an application that scans a text file for certain words, if these words are found a DB table is updated. im scanning through the file line by line for certain words like so

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);

my program is successfully picking up the words but is filling the database multiple times with them. eg. word1,word2,word2 are sent to DB and on second click the DB has word1,word2,word2,word1,word2,word2 and so on.

I call the scanFile method with a button click and any time that happens the words are re-entered ino the db.

I wish for my program to only insert each instance of a word once. so after the file has been read line by line perhaps the best course of action would be to empty the file ?? or maybe a different approach with my loop is needed

here is the insert method also

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

any advice much appreciated, I've been stuck on this for hours .

Aucun commentaire:

Enregistrer un commentaire