本文介绍一款开源的基于JAVA的 Mongodb JDBC 驱动使用教程
https://gitee.com/bgong/jdbc-mongodb-driver
https://blog.csdn.net/gongbing798930123/article/details/135003268
《【开源Mongdb驱动】SpringBoot+Mybatis+Mongdb融合使用教程》
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.11.2</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>bson</artifactId>
<version>3.11.2</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>com.mongo.jdbc</groupId>
<artifactId>jdbc-mongodb-driver</artifactId>
<version>1.0.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/libs/mongo-connector-java-1.0.0.jar</systemPath>
</dependency>
POM文件说明
mongo-connector-java-1.0.0.jar 因为没有放到meavn的公共库里面去,所以需要在开源地址下载里面对应的驱动包放在项目里面或者本地meavn仓库中。
package com.mongo.jdbc.example;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
*
* @author:binggong
* @createtime: 2023年12月10日 下午2:35:47
* @version:V.0.1
* @tag: mongodb jdbc 操作
*
*/
public class JdbcMongoCommandExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Class.forName("com.mongo.jdbc.Driver");
/**
* 连接方案1
*/
// Properties properties = new Properties();
// properties.put("user", "");
// properties.put("password", "");
// properties.put("address", "localhost:27017");
// properties.put("dbname","demo_db");
// properties.put("isSSL","false");
// Connection conn = DriverManager.getConnection("", properties);
/**
* 连接方案2
* jdbc:mongo://localhost:27017/db_name?isSSL=false
*/
String jdbcUrl ="jdbc:mongo://localhost:27017/demo_db?isSSL=false";
Connection conn = DriverManager.getConnection(jdbcUrl, null, null);
//写入操作
String insertScript= "db.tb_user.insert({\"deptno\":?,\"dname\":?,\"loc\":?});";
PreparedStatement ps = conn.prepareStatement(insertScript);
ps.setInt(1, 1);
ps.setString(2, "数据中台部");
ps.setString(3, "湖北武汉");
ps.execute();
//查询数据
String queryScript = "db.tb_user.find()";
ps = conn.prepareStatement(queryScript);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
String _id = rs.getString("_id");
String deptno = rs.getString("deptno");
String dname = rs.getString("dname");
String loc = rs.getString("dname");
System.out.println("_id:"+_id+"|deptno:"+deptno+"|dname:"+dname+"|loc:"+loc);
}
//删除数据
String deleteScript = "db.tb_user.deleteMany({'loc':?})";
ps = conn.prepareStatement(deleteScript);
ps.setString(1, "湖北武汉");
ps.execute();
ps.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
例如:jdbc:mongo://localhost:27017/db_name?isSSL=false
jdbc:mongo://为固定标示,标示为mongodb jdbc 驱动连接串
localhost:27017 :连接的主机和短裤
db_name :为数据库名称
isSSL=false :mongodb连接配置参数,如有多配置参加可以在后面用&keyxx=valuex 追加