apache phoenix的JAVA JDBC操作是怎样的,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
引入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);
}
}
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注天达云行业资讯频道,感谢您对天达云的支持。