Quick Demo

This section provides a quick demo to help you get started with the DolphinDB Java API. It includes connecting to, and interacting with a standalone DolphinDB server.

Establishing Connection

Java API uses DBConnection to execute scripts and functions on the DolphinDB server and facilitates data transfer between clients and servers.

The following example connects to a DolphinDB server as a guest user and executes a simple script. Make sure the DolphinDB server is started before establishing a connection.

Note: The variables YourHost and YourPort in the following TestDemo class should be specified as your actual host and port.

public class TestDBConnection {
    private static final String HOST = "localhost"; 
    private static final int PORT = 8848; 

    DBConnection dbConnection = new DBConnection();

    @Test
    public void testDBConnectAndRun() throws IOException {
        dbConnection.connect(HOST, PORT);
        Entity entity = dbConnection.run("x = 1+1; x;");
        dbConnection.close();
        
        System.out.println(entity.getString());
    }
}

Expected output:

Connect to localhost:8848.
2

Some functions (such as getFunctionViews) can only be executed with appropriate privileges. The following example connects to a DolphinDB server as an admin and executes a simple script.

public class TestDBConnection {
    private static final String HOST = "localhost"; 
    private static final int PORT = 8848; 
    private static final String USER = "admin"; 
    private static final String PASSWORD = "123456"; 

    DBConnection dbConnection = new DBConnection();

    @Test
    public void testAdminUserConnectAndRun() throws IOException {
        dbConnection.connect(HOST, PORT, USER, PASSWORD);
        Entity entity = dbConnection.run("getFunctionViews()");
        System.out.println(entity.getString());
    }
}

The output is expected to contain the function views saved on the DolphinDB server.

name    body                                                   
------- -------------------------------------------------------------
CONCAT1 def CONCAT1(X, Y){
  return string(X) + string(Y)
}    
instr   def instr(string1, string2, start_position = NULL, n...
nvl2    def nvl2(col, result1, result2){
  return iif(! isNu...

For a non-admin user, the following exception will be thrown:

java.io.IOException: 192.168.0.68:8848 Server response: 'getFunctionViews() => Only administrators can use function getFunctionViews.' script: 'getFunctionViews()'
Note: It is recommended to call close() immediately to close the session when DBConnection is no longer in use. Otherwise too many connections might prevent other connections from accessing the server.