为何无法将文本框取值添加至MongoDB数据库?
解决MongoDB数据插入无响应问题
问题根源及修复方案
缺少异常捕获,错误静默发生
MongoDB操作可能抛出网络异常、权限错误、字段验证失败等问题,但你的代码没有任何异常处理逻辑,一旦出错会直接静默失败,既不会提示用户,也无法定位问题。必须添加try-catch块捕获异常,输出错误信息或给用户提示。在Swing事件线程中执行耗时操作
Swing的actionPerformed方法运行在事件调度线程(EDT)中,MongoDB的网络请求属于耗时操作,会阻塞EDT导致UI卡死,看起来按钮点击无反应。需要把数据库操作放到单独的线程中执行。重复创建/关闭MongoClient
每次点击按钮都新建MongoClient实例,既浪费资源又可能引发连接问题。应该全局复用一个MongoClient实例,仅在程序退出时关闭。字段赋值笔误
代码中append("user", text.getText())是错误的,应该取用户输入的user文本框值(比如user.getText()),而非重复使用text文本框的内容。
修改后的代码示例
// 全局复用MongoClient,避免重复创建 private MongoClient mongoClient; // 在窗口构造方法中初始化MongoClient public YourWindowClass() { // ... 其他UI初始化代码 try { mongoClient = MongoClients.create("mongodb+srv://admin:test2608@cluster0.mfwsdkr.mongodb.net/compia?retryWrites=true&w=majority"); } catch (MongoException e) { JOptionPane.showMessageDialog(null, "数据库连接失败:" + e.getMessage()); e.printStackTrace(); } addButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // 先获取并校验输入值 String logId = logID.getText().trim(); String processName = processName.getText().trim(); String type = type.getText().trim(); String textContent = text.getText().trim(); String user = user.getText().trim(); // 修正字段来源 if (logId.isEmpty() || processName.isEmpty() || type.isEmpty() || textContent.isEmpty() || user.isEmpty()) { JOptionPane.showMessageDialog(null, "请填写所有必填字段"); return; } // 启动单独线程执行数据库操作 new Thread(() -> { try { MongoDatabase database = mongoClient.getDatabase("compia"); MongoCollection<Document> collection = database.getCollection("Logs"); Document document = new Document("logID", logId) .append("processName", processName) .append("type", type) .append("text", textContent) .append("user", user); collection.insertOne(document); // 回到EDT线程更新UI提示 SwingUtilities.invokeLater(() -> { JOptionPane.showMessageDialog(null, "插入成功"); // 清空文本框 logID.setText(""); processName.setText(""); type.setText(""); text.setText(""); user.setText(""); }); } catch (MongoException ex) { SwingUtilities.invokeLater(() -> { JOptionPane.showMessageDialog(null, "插入失败:" + ex.getMessage()); }); ex.printStackTrace(); } }).start(); } }); } // 窗口关闭时关闭MongoClient @Override protected void processWindowEvent(WindowEvent e) { if (e.getID() == WindowEvent.WINDOW_CLOSING) { if (mongoClient != null) { mongoClient.close(); } super.processWindowEvent(e); } }
内容的提问来源于stack exchange,提问作者Glazed Donut
相关产品推荐
相关产品推荐

