Home > Software engineering >  Java How to use lambda function to insert records into MySQL columns
Java How to use lambda function to insert records into MySQL columns

Time:12-08

I am trying to figure out how I can use this lambda function to insert data into my MySQL database. I am using Java and do not have any errors anywhere else in the code. The reason I have it sorted is because I am putting it into the database in an order. The words with the highest count in the text are at the top of the database list.

map.entrySet().stream().sorted((k1, k2) -> -k1.getValue().compareTo(k2.getValue()))             
            .forEach(k -> out.println(k.getKey()   ": "   k.getValue()));

I am receiving errors when I try to set

pst.setInt(1, k.getValue());
pst.setString(2, k.getKey());

Here is the rest of my code

public class SomeRandomName {

static Map<String, Integer> count(Scanner scanner) {
    Map<String, Integer> words = new LinkedHashMap<>();
    while (scanner.hasNext()) {
        words.merge(scanner.next(), 1, Integer::sum);
    }
    return words;
}

public static void main(String[] args) throws IOException {
    
    try (Scanner scanner = new Scanner(new File("FlyingRats.txt")).useDelimiter("\\W ")) {
        Map<String, Integer> map = null;
        try {
            map = count(scanner);
        } catch (Exception e) {
            e.printStackTrace();
        }
                
        try(FileWriter fw = new FileWriter("FlyingRats.txt", true);
                BufferedWriter bw = new BufferedWriter(fw);
                PrintWriter out = new PrintWriter(bw)) {
            
            map.entrySet().stream().sorted((k1, k2) -> -k1.getValue().compareTo(k2.getValue()))             
            .forEach(k -> out.println(k.getKey()   ": "   k.getValue()));
                                    
    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    String url = "jdbc:mysql://localhost:3306/eagle_scoutleader";
    String user = "root";
    String password = "**********";
    
    String sql = "INSERT INTO cats(wordCount, wordName) VALUES(?,?)";
    String query = "SELECT * FROM cats";
    
    try (Connection con = DriverManager.getConnection(url, user, password);
            PreparedStatement pst = con.prepareStatement(sql)) {
        
            pst.setInt(1, k.getValue());
            pst.setString(2, k.getKey());
            pst.executeUpdate(); 
        
            Statement statement = con.createStatement();                

            ResultSet rs = statement.executeQuery(query);             

        while (rs.next()) {
           System.out.print(rs.getInt(1));              
           System.out.print(": ");
           System.out.print(rs.getInt(2)   " ");
           System.out.println(rs.getString(3));
       }
                        
    } catch (SQLException ex) {
        
        Logger lgr = Logger.getLogger(SomeRandomName.class.getName());
        lgr.log(Level.SEVERE, ex.getMessage(), ex);       
    }
} }
}}

Here is the error I am receiving if I run the code: The errors are on the same line as I state above.

Exception in thread "main" java.lang.Error: Unresolved compilation problems: k cannot be resolved k cannot be resolved at database.DatabaseINSERT.main(DatabaseINSERT.java:85)

CodePudding user response:

One possibility would be:

try (Connection con = DriverManager.getConnection(url, user, password);
     PreparedStatement pst = con.prepareStatement(sql)) {

  map.entrySet()
      .stream()
      .sorted((k1, k2) -> -k1.getValue().compareTo(k2.getValue()))
      .forEach(k -> {
        try {
          pst.setInt(1, k.getValue());
          pst.setString(2, k.getKey());
          pst.executeUpdate();
        } catch (SQLException e) {
          throw new RuntimeException(e);
        }
      });
} catch (Exception ex) {
  // handle errors
}

You could also skip the .sorted() and the .stream() steps.

But I don't see any necessity to use lambdas here. This would work, too:

try (Connection con = DriverManager.getConnection(url, user, password);
     PreparedStatement pst = con.prepareStatement(sql)) {
  for (Map.Entry<String, Integer> entry : map.entrySet()) {
    pst.setInt(1, entry.getValue());
    pst.setString(2, entry.getKey());
    pst.executeUpdate();
  }
} catch (Exception ex) {
  // handle errors
}

This makes the code a bit cleaner.

  • Related