1 shell命令操作hbase
可以把Phoenix和hbase的结合理解为类似MySQL的关系型数据库,这样比较便于理解使用。
Phoenix的crud和标准的SQL十分类似。
//创建表
create table IF NOT EXISTS test.Person (IDCardNum INTEGER not null primary key, Name varchar(20),Age INTEGER);
//插入数据
upsert into test.Person (IDCardNum,Name,Age) values (100,'Tom',12);
upsert into test.Person (IDCardNum,Name,Age) values (101,'Jerry',13);
upsert into test.Person (IDCardNum,Name,Age) values (102,'Mike',14);
//添加列
ALTER TABLE test.Person ADD sex varchar(10);
//更新数据
upsert into test.person (idcardnum,sex) values (100,'male');
upsert into test.person (idcardnum,sex) values (102,'male');
//删除数据
delete from test.Person where idcardnum=100;
//删除表
drop table test.person;
2 使用Phoenix api来操作hbase
import java.sql.*;
public class Test {
static final String DRIVER = "org.apache.phoenix.jdbc.PhoenixDriver"; //类似于MySQL的驱动
static final String URL = "jdbc:phoenix:10.62.127.137:2181"; //连接Phoenix的地址,与MySQL类似
public static void main(String[] args) {
String sql = "select * from test.person";
String sql1 = "upsert into test.Person (IDCardNum,Name,Age) values (102,'Mike',14)";
String sql2 = "upsert into test.person (idcardnum,sex) values (102,'male')";
Test test = new Test();
test.getConn();
try {
test.HandPhoemix(sql2);
test.select(sql);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 建立连接
* 与MySQL类似
*/
public Connection getConn() {
Connection conn = null;
try {
Class.forName(DRIVER);
if (conn == null) {
conn = DriverManager.getConnection(URL);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
/**
* 查询表
* 与MySQL类似
*/
public void select(String sql) throws SQLException {
Connection conn = getConn();
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery(sql);
while (result.next()) {
System.out.print("id: " + result.getInt("IDCARDNUM"));
System.out.print(" name: " + result.getString("NAME"));
System.out.print(" sex: " + result.getString("sex"));
System.out.println(" age: " + result.getInt("age"));
}
result.close();
stmt.close();
conn.close();
}
/**
* 根据不同的sql语句进行插入、更新、删除表
* 与MySQL类似
*/
public void HandPhoemix(String sql) throws SQLException {
Connection conn = getConn();
Statement stmt = conn.createStatement();
stmt.executeUpdate(sql);
conn.commit();
stmt.close();
conn.close();
}
}