Skip to main content

Install & Configure

Hint

This article is generated by AI translation.

Add Dependency

Before using jdbc-mongo, add the Maven dependency. Current version: 6.5.0

<dependency>
<groupId>net.hasor</groupId>
<artifactId>jdbc-mongo</artifactId>
<version>6.3.0</version> <!-- Use the latest version -->
</dependency>

JDBC Connection

Use a standard JDBC URL to connect.

jdbc:dbvisitor:mongo://<host>:<port>/<database>?<parameters>
  • host: MongoDB server address.
  • port: MongoDB server port (default 27017).
  • database: database name.
  • parameters: connection parameters; see Parameters.

Example

public class MongoJdbcExample {
public static void main(String[] args) throws Exception {
String url = "jdbc:dbvisitor:mongo://127.0.0.1:27017/testdb";
try (Connection conn = DriverManager.getConnection(url)) {
// Statement Example
try (Statement stmt = conn.createStatement()) {
try (ResultSet rs = stmt.executeQuery("db.my_collection.find().limit(10)")) {
while (rs.next()) {
System.out.println(rs.getString("name"));
}
}
}

// PreparedStatement Example
try (PreparedStatement pstmt = conn.prepareStatement("db.my_collection.find({name:?})")) {
pstmt.setString(1, "mali");
try (ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
System.out.println(rs.getString("name"));
}
}
}
}
}
}