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); } }
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。