转:http://blog.csdn.net/jiangshouzhuang/article/details/53823234
Kylin提供了标准的ODBC和JDBC接口,能够和传统BI工具进行很好的集成。分析师们可以用他们最熟悉的工具来享受Kylin带来的快速。
本章节介绍通过Java程序调用Kylin的JDBC接口访问Kylin的Cube数据。
首先我们来看一下连接Kylin的URL格式为:
jdbc:kylin://<hostname>:<port>/<kylin_project_name>
注:
如果“ssl”为true话,那么上面的端口号应该为Kylin服务的HTTPS端口号。
kylin_project_name必须指定,并且在Kylin服务中存在。
下面介绍几种方式访问Kylin数据:
第一种方法:使用Statement方式查询
示例完整代码如下:
- package com.my.kylin;
- import java.sql.Connection;
- import java.sql.Driver;
- import java.sql.ResultSet;
- import java.sql.Statement;
- import java.util.Properties;
- public class QueryKylinST {
- public static void main(String[] args) throws Exception {
- // 加载Kylin的JDBC驱动程序
- Driver driver = (Driver) Class.forName("org.apache.kylin.jdbc.Driver").newInstance();
- // 配置登录Kylin的用户名和密码
- Properties info= new Properties();
- info.put("user","ADMIN");
- info.put("password","KYLIN");
- // 连接Kylin服务
- Connection conn= driver.connect("jdbc:kylin://192.168.1.128:7070/learn_kylin",info);
- Statement state= conn.createStatement();
- ResultSet resultSet =state.executeQuery("select part_dt, sum(price) as total_selled,count(distinct seller_id) as sellers " +
- "from kylin_sales group by part_dt order by part_dt limit 5");
- System.out.println("part_dt\t"+ "\t" + "total_selled" + "\t" +"sellers");
- while(resultSet.next()) {
- String col1 = resultSet.getString(1);
- String col2 = resultSet.getString(2);
- String col3 = resultSet.getString(3);
- System.out.println(col1+ "\t" + col2 + "\t" + col3);
- }
- }
- }
在eclipse中执行之前先引入Kylin的Jar包,如图所示:
运行结果为:
第二种方法:使用PreparedStatement方式查询
这种方式支持在SQL语句中传入参数,支持如下的方法设置参数:
l setString
l setInt
l setShort
l setLong
l setFloat
l setDouble
l setBoolean
l setByte
l setDate
l setTime
l setTimestamp
示例完整代码如下:
- package com.my.kylin;
- import java.sql.Connection;
- import java.sql.Driver;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.util.Properties;
- public class AnylistWithPS {
- public static void main(String[] args) throws Exception {
- anylist();
- }
- public static void anylist() throws Exception {
- Driver driver =(Driver) Class.forName("org.apache.kylin.jdbc.Driver").newInstance();
- Properties info= new Properties();
- info.put("user","ADMIN");
- info.put("password","KYLIN");
- Connection conn= driver.connect("jdbc:kylin://192.168.1.128:7070/learn_kylin",info);
- PreparedStatement state = conn.prepareStatement("select * from KYLIN_CATEGORY_GROUPINGS where LEAF_CATEG_ID = ?");
- state.setLong(1,10058);
- ResultSet resultSet = state.executeQuery();
- while (resultSet.next()) {
- String col1 = resultSet.getString(1);
- String col2 = resultSet.getString(2);
- String col3 = resultSet.getString(3);
- System.out.println(col1+ "\t" + col2 + "\t" + col3);
- }
- }
- }
运行结果如下图所示: