Create a new connection
The first step towards interacting with SurrealDB is to create a new connection to a database instance. This involves initializing a new instance of the Surreal class and connecting it to a database endpoint. You can then switch to a specific namespace and database, and pass required authentication credentials.
This guide will walk you through the process of creating a new connection to a SurrealDB instance using the Java SDK.
Opening a connection
The .connect() method accepts a String pointing to the desired local or remote instance. Since the Java SDK supports running embedded databases, you can also specify an embedded endpoint such as memory:// and surrealkv://.
Supported protocols
This is the complete list of supported connection protocols. For more on connection parameters, see the start command documentation.
http:// - Plain HTTPhttps:// - Secure HTTPws:// - Plain WebSocketwss:// - Secure WebSocketmemory:// - In-memory databasesurrealkv:// - Disk-based databasesurrealkv://?versioned=true - Disk-based database (with temporal data)
http:// - Plain HTTPhttps:// - Secure HTTPws:// - Plain WebSocketwss:// - Secure WebSocketmemory:// - In-memory databasesurrealkv:// - Disk-based databasesurrealkv+versioned:// - Disk-based database (with temporal data)
Selecting a namespace and database
Depending on the complexity of your use case, you can switch to a specific namespace and database using the .useNs() and .useDb() methods. This is particularly useful if you want to switch to a different setup after connecting. You can also stay in the same namespace but switch to a different database.
Example usage
driver.useNs("surrealdb").useDb("docs");
Closing the connection
The .close() method closes the persistent connection to the database. You should always call this method when you are done with the connection to free up resources. You can use a try-with-resources block to ensure that the connection is closed automatically when the block is exited.
driver.close();
try (Surreal driver = new Surreal()) {
}
Example
Here is an example of the .connect(), .useNs(), .useDb(), and .close() methods in action.
Example.java
package com.surrealdb.example;
import com.surrealdb.Surreal;
public class Example {
public static void main(String[] args) {
try (final Surreal driver = new Surreal()) {
driver.connect("memory");
driver.useNs("surrealdb").useDb("docs");
}
}
}