如何使用 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
廣告