Connecting to GeoSpock database using JDBC

You can connect to the GeoSpock database from within a Java program using Java Database Connectivity (JDBC).

Before writing code that uses JDBC, install the JDBC driver. For guidance on how to do this, refer to the installation instructions.

Alternatively, if you are using Maven to manage your Java project, follow the instructions on how to add the dependency for the Presto JDBC driver to your project.

Example Java program

This example Java program demonstrates how to connect to GeoSpock database over a JDBC connection.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.Properties;

class ExamplePrestoJDBC
{ 
    public static void main(String args[]) { 
        Properties properties = new Properties();
        properties.put("user", "<user>");
        properties.put("password", "<password>");
		properties.put("SSL", "true");

        String url = "jdbc:presto://<host>:8446";
        
        try (java.sql.Connection connectionSQL = DriverManager.getConnection(url, properties);
             Statement statement = connectionSQL.createStatement();
             ResultSet resultSet = statement.executeQuery(args[0])) {

			ResultSetMetaData metadata = resultSet.getMetaData();
			int columns = metadata.getColumnCount();

			for (int i = 1; i < columns; i++) {
				System.out.print(metadata.getColumnName(i) + ", ");
			}
			System.out.print(metadata.getColumnName(columns) + "\n");
			
            while (resultSet.next()) {
            	for (int i = 1; i < columns; i++) {
            		System.out.print(resultSet.getString(i) + ", ");
            	}
            	System.out.print(resultSet.getString(columns) + "\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } 
}

Substitute the <host>, <user> and <password> strings for the GeoSpock database's hostname, and your username and password for your GeoSpock database account.

To compile and run this example script, use the following commands:

javac ExamplePrestoJDBC.java

java ExamplePrestoJDBC ‘SELECT * FROM geospock.example.table’