SurrealDB Docs Logo

Enter a search query

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.

MethodDescription
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

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

  • http:// - Plain HTTP
  • https:// - Secure HTTP
  • ws:// - Plain WebSocket
  • wss:// - Secure WebSocket
  • memory:// - In-memory database
  • surrealkv:// - Disk-based database

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.

// Close the connection manually driver.close(); // Using try-with-resources 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()) { // Connect to an in-memory database driver.connect("memory"); // Select a namespace and database driver.useNs("surrealdb").useDb("docs"); } } }
© SurrealDB GitHub Discord Community Cloud Features Releases Install