如何使用 JDBC 程序连接到 MongoDB 数据库?
MongoDB 是一个跨平台面向文档的数据库,提供高性能、高可用性和易于扩展。MongoDB 基于集合和文档的概念。
在开始在你中连接 MongoDB 之前,你需要确保你拥有 MongoDB JDBC 驱动程序。如果没有,请从路径 下载 mongo.jar 下载 jar,并将它添加到你的类路径。
示例
以下 JDBC 程序建立了与 MongoDB 数据库的连接,并在其中创建了一个集合。
import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class CreatingCollection {
public static void main( String args[] ) {
// Creating a Mongo client
MongoClient mongo = new MongoClient( "localhost" , 27017 );
// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb", "password".toCharArray());
System.out.println("Connected to the database successfully");
//Accessing the database
MongoDatabase database = mongo.getDatabase("myDb");
//Creating a collection
database.createCollection("sampleCollection");
System.out.println("Collection created successfully");
}
}输出
Connected to the database successfully Collection created successfully
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP