java - 将 MongoDB 集合中的数据检索到 Swing JTable 中

标签 java swing mongodb jtable mongodb-java

我是数据库项目的新手。 我不知道如何在将 mongodb 连接到数据库服务器后在 Swing 窗口(编辑:JTable)内显示 mongodb 中的集合....请帮我解决这个... 我已经尝试在 sql 中执行此操作,但无法使用 mongodb 执行此操作

JButton btnDisplay = new JButton("display");
    btnDisplay.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                // To connect to mongodb server
                MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
                // Now connect to your databases
                DB db = mongoClient.getDB( "test" );
                System.out.println("Connect to database successfully");

                DBCollection coll = db.getCollection("cars");
                DBCursor cursor = coll.find();
            }

            catch (Exception a) {
                a.printStackTrace();
            }
        }
    });

最佳答案

DBCursor意味着要迭代。您可以使用 DBCursor#hasNext()就像普通的迭代器一样,而 DBCursor#next()获取下一个DBObjectDBObject 允许您getMap 一样的值,通过传入键

假设我们在 swingtest 数据库中有一个集合,其中包含以下文档

{ "_id" : ObjectId("5450700691a43786388fcc8f"), "first" : "Stack", "last" : "Overflow" }
{ "_id" : ObjectId("5450704d91a43786388fcc90"), "first" : "Pee", "last" : "Skillet" }
{ "_id" : ObjectId("5450705a91a43786388fcc91"), "first" : "Hello", "last" : "World" }
{ "_id" : ObjectId("545070b091a43786388fcc92"), "first" : "Mongo", "last" : "DB" }

您实际上还没有指定要对集合执行什么操作,所以假设您要将数据添加到 JTable 中,您可以执行类似的操作

MongoClient mongoClient = null;
DBCursor cursor = null;
try {
    mongoClient = new MongoClient( "localhost" , 27017 );
    DB db = mongoClient.getDB( "swingtest" );
    DBCollection coll = db.getCollection("table");
    cursor = coll.find();

    String[] columnNames = {"id", "First", "Last"};
    DefaultTableModel model = new DefaultTableModel(columnNames, 0);

    while(cursor.hasNext()) {
        DBObject obj = cursor.next();
        String first = (String)obj.get("first");
        String last = (String)obj.get("last");
        ObjectId id = (ObjectId)obj.get("_id");
        model.addRow(new Object[] { id, first, last });
    }
    table.setModel(model);

    cursor.close(); 
    mongoClient.close();
}

对于每次迭代(文档),我们获取 _idfirstlast 值,然后创建一行,在其中添加 DefaultTableModel。在迭代结束时,我们设置 JTable 的模型。

这是完整的示例

enter image description here

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import org.bson.types.ObjectId;

public class MongoStackoverflow {
    private static JTable table;

    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            public void run() {
                table = new JTable(){
                    @Override
                    public Dimension getPreferredScrollableViewportSize() {
                        return new Dimension(300, 150);
                    }
                };
                JPanel panel = new JPanel(new BorderLayout());
                JButton button = new JButton("Show Data");
                button.addActionListener(listener);
                panel.add(new JScrollPane(table));
                panel.add(button, BorderLayout.PAGE_END);
                JOptionPane.showMessageDialog(null, panel);
            }
        };
        SwingUtilities.invokeLater(runnable);
    }

    static ActionListener listener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            MongoClient mongoClient = null;
            DBCursor cursor = null;
            try {
                mongoClient = new MongoClient( "localhost" , 27017 );
                DB db = mongoClient.getDB( "swingtest" );
                DBCollection coll = db.getCollection("table");
                cursor = coll.find();

                String[] columnNames = {"id", "First", "Last"};
                DefaultTableModel model = new DefaultTableModel(columnNames, 0);

                while(cursor.hasNext()) {
                    DBObject obj = cursor.next();
                    String first = (String)obj.get("first");
                    String last = (String)obj.get("last");
                    ObjectId id = (ObjectId)obj.get("_id");
                    model.addRow(new Object[] { id, first, last });
                }
                table.setModel(model);

                cursor.close(); 
                mongoClient.close();
            } catch (UnknownHostException ex) {
                Logger.getLogger(MongoStackoverflow.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                if (cursor!= null) {
                    cursor.close();
                }
                if (mongoClient != null) {
                     mongoClient.close();
                }   
            }
        }
    }; 
}
<小时/>

资源

关于java - 将 MongoDB 集合中的数据检索到 Swing JTable 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26616072/

相关文章:

java - 突出显示 jtable 中的单元格

javascript - 插入/更新子元素或在集合中插入完整文档 - 取决于现有的主元素

java - 打印不重复的字符元素

java - Android:将JSON对象值转换为指定类

java - 电子邮件回复表明电子邮件打开和收到的时间

java - 通过 WinAPI 提取光标大小(Windows 10)

java - 使用鼠标事件 : Am I doing this correctly?

java - 显示 RTP MJPEG

node.js - Mongoose 排序嵌套的对象数组不起作用

node.js - 该帐户未启用聚合管道