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.
| Method | Description |
|---|---|
driver.connect(String url) | Connects to a local, remote, or embedded database endpoint |
driver.close() | Closes the persistent connection to the database |
driver.useNs(String namespace) | Switch to a specific namespace |
driver.useDb(String database) | Switch to a specific database |
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://.
This is the complete list of supported connection protocols
http:// - Plain HTTPhttps:// - Secure HTTPws:// - Plain WebSocketwss:// - Secure WebSocketmemory:// - In-memory databasesurrealkv:// - Disk-based databasesurrealkv+versioned:// - Disk-based database (with temporal data)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.
driver.useNs("surrealdb").useDb("docs");
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.
// Close the connection manually driver.close(); // Using try-with-resources try (Surreal driver = new Surreal()) { // ... }
Here is an example of the .connect(), .useNs(), .useDb(), and .close() methods in action.
Example.javapackage com.surrealdb.example; import com.surrealdb.Surreal; public class Example { public static void main(String[] args) { try (final Surreal driver = new Surreal()) { // Connect to an in-memory database driver.connect("memory"); // Select a namespace and database driver.useNs("surrealdb").useDb("docs"); } } }