引入jar 到pom
org.apache.hadoop
hadoop-client
2.5.2
org.apache.hbase
hbase-client
1.0.1.1
org.apache.phoenix
phoenix-core
4.4.0-HBase-1.0
创建工具类
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);
}
}