import org.apache.hadoop.conf.Configuration;
import?org.apache.hadoop.hbase.*;
import?org.apache.hadoop.hbase.client.*;
import
java.io.IOException;
public?class?ExampleForHbase{
public?static?Configuration?configuration;
public?static?Connection?connection;
public?static?Admin?admin;
//主函數(shù)中的語句請逐句執(zhí)行医增,只需刪除其前的//即可革砸,如:執(zhí)行insertRow時請將其他語句注釋
public?static?void?main(String[]?args)throws?IOException{
createTable("Score",new?String[]{"Studnet","Course","SC"});
}
//建立連接
public?static?void?init(){
configuration??=?HBaseConfiguration.create();
configuration.set("hbase.rootdir","hdfs://localhost:9000/hbase");
try{
connection?=?ConnectionFactory.createConnection(configuration);
admin?=?connection.getAdmin();
}catch?(IOException?e){
e.printStackTrace();
}
}
//關(guān)閉連接
public?static?void?close(){
try{
if(admin?!=?null){
admin.close();
}
if(null?!=?connection){
connection.close();
}
}catch?(IOException?e){
e.printStackTrace();
}
}
/**
*?建表常潮。HBase的表中會有一個系統(tǒng)默認(rèn)的屬性作為主鍵徐鹤,主鍵無需自行創(chuàng)建悯蝉,默認(rèn)為put命令操作中表名后第一個數(shù)據(jù),因此此處無需創(chuàng)建id列
*?@param?myTableName?表名
*?@param?colFamily?列族名
*?@throws?IOException
*/
public?static?void?createTable(String?tableName,String[]?fields)?throws?IOException?{
init();
TableName?tablename?=?TableName.valueOf(tableName);
if(admin.tableExists(tablename)){
System.out.println("table?is?exists!");
admin.disableTable(tablename);
admin.deleteTable(tablename);//刪除原來的表
}else{
HTableDescriptor?hTableDescriptor?=?new?HTableDescriptor(tablename);
for(String?str:fields){
HColumnDescriptor?hColumnDescriptor?=?new?HColumnDescriptor(str);
hTableDescriptor.addFamily(hColumnDescriptor);
}
admin.createTable(hTableDescriptor);
System.out.println("create?table?success");
}
close();
}
}