使用动态数据插入MySQL表时遭遇SQL语法错误求助
问题分析与解决方案
核心错误原因
报错Unknown column 'countNumber' in 'field list'的直接原因是INSERT语句中使用的字段名与MySQL表word的实际字段名不匹配:
- 表实际字段:
wordCount(存储词频)、wordName(存储单词) - 代码中错误使用:
countNumber、countName
另外recordNumber是自增字段,插入时无需手动指定,数据库会自动生成。
修正步骤
1. 修正SQL插入语句
替换为表实际存在的字段名:
String sql = "INSERT INTO word(wordCount, wordName) VALUES(?,?)";
2. 修复排序逻辑
原代码将排序放在for循环内部,会每次打乱count与words的对应关系(词频和单词不再匹配)。需将排序移到循环外,且同时对单词和词频进行关联排序。
3. 优化数据库连接
原代码在循环内重复创建数据库连接,会造成资源浪费。应将连接创建移到循环外,全程复用同一个连接。
4. 优化词频统计效率(可选)
原ArrayList统计方式为O(n²)复杂度,大文本下效率低,改用HashMap<String, Integer>可将复杂度降至O(n)。
完整修正代码
import java.io.FileInputStream; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; public class DatabaseGO { public static void main(String[] args) throws IOException { // 用HashMap高效统计词频 Map<String, Integer> wordCountMap = new HashMap<>(); FileInputStream findIt = new FileInputStream("theraven.txt"); Scanner fileInput = new Scanner(findIt); while (fileInput.hasNext()) { String nextWord = fileInput.next(); // 可选:统一单词大小写,避免"The"和"the"被统计为不同单词 // nextWord = nextWord.toLowerCase(); wordCountMap.put(nextWord, wordCountMap.getOrDefault(nextWord, 0) + 1); } fileInput.close(); findIt.close(); // 将Map转换为List,按词频降序排序 List<Map.Entry<String, Integer>> sortedWordList = new ArrayList<>(wordCountMap.entrySet()); sortedWordList.sort(Comparator.comparing(Map.Entry::getValue, Collections.reverseOrder())); // 数据库连接参数 String url = "jdbc:mysql://localhost:3306/word_occurrences"; String user = "root"; String password = "kittylitter"; String sql = "INSERT INTO word(wordCount, wordName) VALUES(?,?)"; // 复用数据库连接,自动管理资源 try (Connection con = DriverManager.getConnection(url, user, password); PreparedStatement pst = con.prepareStatement(sql)) { // 批量插入提升效率 for (Map.Entry<String, Integer> entry : sortedWordList) { pst.setInt(1, entry.getValue()); pst.setString(2, entry.getKey()); pst.addBatch(); } pst.executeBatch(); } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseGO.class.getName()); lgr.log(Level.SEVERE, ex.getMessage(), ex); } } }
额外说明
- 批量插入:使用
addBatch()和executeBatch()减少数据库交互次数,大幅提升大量数据插入的效率。 - 大小写处理:根据需求决定是否统一单词大小写,避免因大小写差异导致统计重复。
- 资源管理:try-with-resources语法会自动关闭Connection、PreparedStatement等资源,避免资源泄漏。
内容的提问来源于stack exchange,提问作者John Hendricks
相关产品推荐
相关产品推荐

