Phoenix JDBC访问

  1. 引入Phoenix jar

在maven项目中引入Phoenix jar包:

<dependency>

            <groupId>org.apache.phoenix</groupId>

            <artifactId>phoenix-core</artifactId>

            <version>4.8.0-HBase-1.1</version>

    </dependency>

备注:版本需与hbase版本一致,否则会出现问题

  1. 使用JDBC 访问Phoenix

Phoenix除了提供SQLLine这种命令方式,同时提供了JDBC代码的访问方式。

package com.dajiangtai.phoenix;

 

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.ResultSetMetaData;

import java.sql.SQLException;

import java.sql.Statement;

/**

* phoenix测试类

* @author John

*

*/

public class PhoenixTest {

    

    public static Connection getConnection(){

        Connection con;

        try {

            //设置连接类名

            Class.forName("org.apache.phoenix.jdbc.PhoenixDriver");

            //设置连接URL

            con = DriverManager.getConnection("jdbc:phoenix:master:2181");

            return con;

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

            return null;

        }

        

    }

    //查询方法

    public void query(String sql) throws SQLException{

        //创建连接

        Connection con = getConnection();

        Statement stmt = con.createStatement();

        

        //执行查询

        ResultSet rs = stmt.executeQuery(sql);

        //获取元数据信息

        ResultSetMetaData rsmd = rs.getMetaData();

        int columnCount = rsmd.getColumnCount();

        

        //获取列名

        StringBuilder sb = new StringBuilder();

        for(int i = 1;i<=columnCount;i++){

            String columnName = rsmd.getColumnLabel(i);

            sb.append(columnName+"\t");

        }

        

        if(sb.length()>0){

            sb.setLength(sb.length()-1);

        System.out.println(sb.toString());

        

        //查询结果

        while(rs.next()){

            sb = new StringBuilder();

            for(int i=1;i<=columnCount;i++){

                sb.append(rs.getString(i)+"\t");

            }

            if(sb.length()>0){

                sb.setLength(sb.length()-1);

            System.out.println(sb.toString());

            }

        }

        }

        //关闭连接

        con.close();

    }

 

    /**

     * @param args

     * @throws SQLException

     */

    public static void main(String[] args) throws SQLException {

        // TODO Auto-generated method stub

        PhoenixTest test = new PhoenixTest();

        //查询Phoenix表WEB_STAT所有记录

        test.query("select * from WEB_STAT");

    }

 

}

执行结果如下所示:

posted @ 2020-12-15 00:26  Simon92  阅读(1465)  评论(0编辑  收藏  举报