一、准备工作
由于笔者的HBase版本为2.1.0而Phoenix的5.x版本都高于本版本,所以读者可以直接采用2.4.0的SDK。同时对于
Phoenix则使用如下的依赖(其中compat需要根据实际HBase的版本进行选择)。
<dependencies><dependency><groupId>org.apache.phoenix</groupId><artifactId>phoenix-core</artifactId><version>5.1.0</version></dependency><dependency><groupId>org.apache.phoenix</groupId><artifactId>phoenix-hbase-compat-2.4.0</artifactId><version>5.1.0</version></dependency></dependencies>
完成以上依赖后我们就可以利用JDBC进行语句执行操作,具体代码示例如下。
public static Connection getConnection() {Connection con;try {Class.forName("org.apache.phoenix.jdbc.PhoenixDriver");con = DriverManager.getConnection("jdbc:phoenix:localhost:2181");return con;} catch (Exception e) {e.printStackTrace();return null;}}@Testpublic void query() throws SQLException {String sql = "select * from db1";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();}
如果读者期望在Spring Boot中利用Mybatis使用Phoenix来操作HBase可以参考本文档
