JDBCのドライバの挙動とかを軽く試したいときに、Javaで普段開発をしていない人にとっては色々初期準備が手間です。
Java9からREPLが標準で備わったという話なので、REPLでJDBCを使って簡単にTreasureDataにクエリを投げれると嬉しいなと思うわけですね。
それではやってみましょう。
Java9以上がインストールされていることを確認する。
$ java -version openjdk version "11.0.2" 2019-01-15 OpenJDK Runtime Environment 18.9 (build 11.0.2+9) OpenJDK 64-Bit Server VM 18.9 (build 11.0.2+9, mixed mode)
PrestoのAPIにアクセスするため、JDBCドライバをローカルにダウンロードしておき、下記にて起動する。
$ jshell --class-path presto-jdbc-0.221.jar | Welcome to JShell -- Version 11.0.2 | For an introduction type: /help intro
下記のよう流れでgetSchemasを利用し、DBの一覧を表示できる。
jshell> import java.sql.DriverManager; jshell> import java.util.Properties; jshell> import java.sql.*; jshell> String url = "jdbc:presto://api-presto.treasuredata.com:443/td-presto/support"; url ==> "jdbc:presto://api-presto.treasuredata.com:443/td-presto/support" jshell> Properties properties = new Properties(); properties ==> {} jshell>properties.setProperty("user", "<TD APIKEY>"); $7 ==> null jshell>properties.setProperty("password", "password"); $8 ==> null jshell>properties.setProperty("SSL", "true"); $9 ==> null jshell>Connection connection = DriverManager.getConnection(url, properties); connection ==> com.facebook.presto.jdbc.PrestoConnection@4b79ac84 jshell> ResultSet rs = connection.getMetaData().getSchemas(); rs ==> com.facebook.presto.jdbc.PrestoResultSet@3d526ad9 jshell> while(rs.next()) {System.out.println(rs.getString(1));} db1 db2 db3 db4 db5
トラブルシューティング
起動時に下記のエラーが発生した。
$ jshell Launching JShell execution engine threw: Failed remote listen: java.util.concurrent.ExecutionException: com.sun.jdi.connect.TransportTimeoutException: timeout waiting for connection @ com.sun.jdi.SocketListen (defaults: timeout=, port=, localAddress=) -- {timeout=timeout=5000, port=port=, localAddress=localAddress=127.0.0.1}
ローカルへの通信がうまくいっていないようなので、ホスト名を確認し、127.0.0.1になっているかをチェックする。
$ uname -n xxxx.local
一時的であれば下記にてhostnameを変更するか
$ sudo hostname 127.0.0.1
/etc/hostsに127.0.0.1があることを確認する。
ちゃんと起動できると下記のように表示される。
$ jshell | Welcome to JShell -- Version 11.0.2 | For an introduction type: /help intro