将MongoDB集合中的数据检索到Swing JTable中 [英] Retrieve data from MongoDB collection into Swing JTable

查看:84
本文介绍了将MongoDB集合中的数据检索到Swing JTable中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是数据库项目的新手. 将其连接到数据库服务器后,我不知道如何在mongodb中的mongodb中显示一个集合....plz在此方面帮助我... 我曾尝试在sql中执行此操作,但无法使用mongodb

I am a newbie in database projects. I don't know how to display a collection in mongodb inside a swing window ( JTable) after connecting it to the database server....plz help me out in this... I have tried doing this in sql but am not able to do using 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() 就像普通的Iterator DBObject . DBObject允许您 get 值,就像您通过输入键

DBCursor is meant to be iterated through. You can use the DBCursor#hasNext() like you would a normal Iterator, and the DBCursor#next() to get the next DBObject. The DBObject allows you to get values like you would a Map, by passing in the key

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

So let's say we have a collection table in the swingtest database, with the following documents

{ "_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中,可以执行类似的操作

You haven't actually specified what you want to do with the collection, so let's say you want to add the data to a JTable, you could do something like

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设置了模型.

where for each iteration (document), we get the _id, first and last values, then create a row in which we add the DefaultTableModel. At the end of the iterating, we set the model for the JTable.

这是完整的例子

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


资源

  • MongoDB Java API Getting Started Guide
  • MongoDB Java API Documentation
  • How to Use Tables

这篇关于将MongoDB集合中的数据检索到Swing JTable中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆