Skip to main content

Java Client

Overview

This page shows an example of how to connect to the AGENT SQL server with any Java application.

Requirements

Drivers

Drivers include jar files which are required to communicate with the server.

Follow these steps to add the driver to the classpath:

1
Download the AGENT SQL Client Driver jar file from the AGENT UI under the Configuration tab.
2
Ensure that the jar file is present inside a directory named driver.

How to connect

1
In the directory where the driver folder is present, create a file Main.java and paste the following code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class Main {
public static void main(String[] args) {
String connectionString = "jdbc:avatica:remote:url=<console_url>?apiKey=<apiKey>"; // Put your connection string here

String query = "SELECT count(*) FROM paqu"; // Put your SQL query here

String apiKey = "<api_key>"; // Set your AGENT API key here. Not required if set in the connection string above

try {
Class.forName("org.apache.calcite.avatica.remote.Driver");

Properties props = new Properties();
props.setProperty("apiKey", apiKey); // Similarly, other properties can be set here

System.out.println("Approve the token request from AGENT!");
Connection connection = DriverManager.getConnection(connectionString, props);

Statement statement = connection.createStatement();

ResultSet resultSet = statement.executeQuery(query);

if (resultSet.next()) {
String count = resultSet.getString(1);
System.out.println("Total count from 'paqu' table: " + count);
}

// Close the resources
resultSet.close();
statement.close();
connection.close();
} catch (ClassNotFoundException e) {
System.err.println("Avatica Driver class not found. Ensure the driver JAR is in the classpath.");
e.printStackTrace();
} catch (SQLException e) {
System.err.println("SQL Exception encountered.");
e.printStackTrace();
}
}
}
Note

At the appropriately marked places, set your AGENT API key in either the connectionString or the apiKey variable, add the console URL in the connectionString and add your SQL query to execute. Modify the code accordingly to handle the resultSet you are expecting.

2
Compile the Java program using the command
javac Main.java

This will create a Main.class file.

3
Execute the code using the following command. This includes the driver files in the classpath which you downloaded.
java -cp "driver/*:." Main
4
Approve the token request from AGENT to get the execution results.