【问题标题】:Java How to use lambda function to insert records into MySQL columnsJava 如何使用 lambda 函数将记录插入 MySQL 列
【发布时间】:2022-12-18 03:10:05
【问题描述】:

我想弄清楚如何使用此 lambda 函数将数据插入到我的 MySQL 数据库中。我正在使用 Java,并且代码中的其他任何地方都没有任何错误。

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

我在尝试设置时收到错误消息

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

这是我的其余代码

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

}

【问题讨论】:

  • “我收到错误”-> 请也在这里发布这些错误。

标签: java mysql


【解决方案1】:

一种可能性是:

    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
    }

【讨论】:

    猜你喜欢
    • 2013-08-18
    • 1970-01-01
    • 2013-11-23
    • 2012-03-18
    • 2020-10-11
    • 2015-01-29
    • 1970-01-01
    • 2016-02-16
    • 1970-01-01
    相关资源
    最近更新 更多