引入jar 到pom <dependency> <groupId>org.apache.hadoop</groupId> <artifactId>hadoop-client</artifactId> <version>2.5.2</version> </dependency> <dependency> <groupId>org.apache.hbase</groupId> <artifactId>hbase-client</artifactId> <version>1.0.1.1</version> </dependency> <dependency> <groupId>org.apache.phoenix</groupId> <artifactId>phoenix-core</artifactId> <version>4.4.0-HBase-1.0</version> </dependency>
建立工具類 import org.apache.log4j.Logger; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * 使用Phoenix提供標準的JDBC鏈接HBase * @author Chenj */ public class PhoenixHelper { private static final Logger LOG = Logger.getLogger(PhoenixHelper.class); private static final String JDBC_DRIVER_CLASS = "org.apache.phoenix.jdbc.PhoenixDriver"; // jdbc:phoenix:192.168.1.19:2181:/hbase中的/hbase爲HBase註冊到zooKeeper的根目錄, 如使用HBase自帶的zooKeeper,默認爲"hbase" private static final String JDBC_URL = "jdbc:phoenix:192.168.1.19:2181:/hbase"; public static Connection getConn(){ try { // 註冊Driver Class.forName(JDBC_DRIVER_CLASS); // 返回Connection對象 return DriverManager.getConnection(JDBC_URL); } catch (SQLException | ClassNotFoundException e ) { e.printStackTrace(); LOG.error("得到鏈接失敗!"); return null; } } public static void closeConn(Connection conn){ try { if (!conn.isClosed()) conn.close(); } catch (SQLException e) { e.printStackTrace(); LOG.error("關閉鏈接失敗!"); } } }
測試 import org.junit.Before; import org.junit.Test; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; /** * 建立表測試 * @author Chenj */ public class TableTest { Connection conn = null; String sql = "CREATE TABLE IF NOT EXISTS user (" + "username VARCHAR NOT NULL," + "password VARCHAR, " + "age INTEGER NOT NULL CONSTRAINT my_pk PRIMARY KEY (username, age))"; @Before public void init(){ conn = PhoenixHelper.getConn(); } @Test public void createTable() throws SQLException { PreparedStatement preparedStatement = conn.prepareStatement(sql); preparedStatement.execute(); PhoenixHelper.closeConn(conn); } @Test public void dropTable() throws SQLException { PreparedStatement preparedStatement = conn.prepareStatement("drop table user"); preparedStatement.execute(); PhoenixHelper.closeConn(conn); } }