Build a Java application that reads a large text file, counts the frequency of each word, and stores the results in a MySQL database.
PLAINFORMAT
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class WordCounter {

    public static Map<String, Integer> countWords(String filePath) throws IOException {
        Map<String, Integer> wordCount = new HashMap<>();

        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] words = line.split("\\s+");
                for (String word : words) {
                    word = word.toLowerCase().replaceAll("[^a-z0-9]", "");
                    if (!word.isEmpty()) {
                        wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
                    }
                }
            }
        }

        return wordCount;
    }

    public static void main(String[] args) {
        if (args.length != 1) {
            System.err.println("Usage: java Main <text_file_path>");
            return;
        }

        String filePath = args[0];

        try {
            Map<String, Integer> wordCounts = WordCounter.countWords(filePath);
            DatabaseManager.saveWordCounts(wordCounts);
            System.out.println("Word counts saved to the database.");
        } catch (IOException e) {
            System.err.println("Error reading the text file: " + e.getMessage());
        } catch (SQLException e) {
            System.err.println("Error saving word counts to the database: " + e.getMessage());
        }
    }
}

class DatabaseManager {

    private static final String DB_URL = "jdbc:mysql://localhost:3306/word_count_db";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "your_password";

    public static void saveWordCounts(Map<String, Integer> wordCounts) throws SQLException {
        try (Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
            String query = "INSERT INTO word_counts (word, count) VALUES (?, ?) ON DUPLICATE KEY UPDATE count = count + ?";
            PreparedStatement statement = connection.prepareStatement(query);

            for (Map.Entry<String, Integer> entry : wordCounts.entrySet()) {
                statement.setString(1, entry.getKey());
                statement.setInt(2, entry.getValue());
                statement.setInt(3, entry.getValue());
                statement.addBatch();
            }

            statement.executeBatch();
        }
    }
}