Updated on 2023-04-12 GMT+08:00

Sample Code Description

Presto JDBC Usage Example

The following code snippet is in the PrestoJDBCExample class and is used to connect JDBC to Presto TPCDS Catalog.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
private static Connection connection;
private static Statement statement;
/** 
 * Only when Kerberos authentication enabled, configurations in presto-examples/conf/presto.properties
 * should be set. More details please refer to https://prestodb.io/docs/0.215/installation/jdbc.html.
*/
private static void initConnection(String url, boolean krbsEnabled) throws SQLException {
    if (krbsEnabled) {
        String filePath = System.getProperty("user.dir") + File.separator + "conf" + File.separator;
        File proFile = new File(filePath + "presto.properties");if (proFile.exists()) {
            Properties props = new Properties();
            try {
                props.load(new FileInputStream(proFile));
            } catch (IOException e) {
                e.printStackTrace();
            }
            connection = DriverManager.getConnection(url, props);
        }
    } else {
          connection = DriverManager.getConnection(url, "presto", null);
    }
    statement = connection.createStatement();
}

private static void releaseConnection() throws SQLException {
    statement.close();
    connection.close();
}

public static void main(String[] args) throws SQLException {
    try {
        /**
         * Replace example_ip with your cluster presto server ip.
         * By default, Kerberos authentication disabled cluster presto service port is 7520, Kerberos
         * authentication enabled cluster presto service port is 7521
         * The postfix /tpcds/sf1 means to use tpcds catalog and sf1 schema, you can use hive catalog as well
         * If Kerberos authentication enabled, set the second param to true.
         * see PrestoJDBCExample#initConnection(java.lang.String, boolean).
         */
        initConnection("jdbc:presto://example_ip:7520/tpcds/sf1", false);
        //initConnection("jdbc:presto://example_ip:7521/tpcds/sf1", true);
        ResultSet resultSet = statement.executeQuery("select * from call_center");
        while (resultSet.next()) {
            System.out.println(resultSet.getString("cc_name") + " : " + resultSet.getString("cc_employees"));
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        releaseConnection();
    }
}