有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

GUI MongoDB中的java数据库实例

我有这个GUI连接到我的MongoDB数据库:

enter image description here

当您插入数据库名称(例如test)并按OK按钮时,我想将我的应用程序连接到MongoDB数据库。 因此,我以这种方式在OK按钮上实现了actionPerformed方法:

public void actionPerformed(ActionEvent e) {
    Database db = new Database(this.textField.getText());
    this.setVisible(false);
    window2 = new Frame2();
    window2.setVisible(true);
    window2.textArea1.append("Connect to database \""+ db.getDb() + "\" successfully!\n\n");
    window2.textArea1.append("Choose a collection:");
}

Frame2是一个新的JFrame,当您按OK时,它将变为可见,并在名为textArea1JTextArea中显示消息
这是数据库类的构造函数:

public Database(String dbName) {        
    super();
    try {
        MongoClient client = new MongoClient("127.0.0.1", 27017);
        this.db = client.getDB(dbName);
    }
    catch(Exception e) {
        System.out.println(e.getMessage());
    }
}

在actionPerformed方法内创建数据库实例是否正确


共 (0) 个答案