| 1 | {{{ |
| 2 | #!html |
| 3 | <div style="text-align: center; color:#151B8D"><big style="font-weight: bold;"><big><big> |
| 4 | ITRI HBase 進階課程 |
| 5 | </big></big></big></div> <div style="text-align: center; color:#7E2217"><big style="font-weight: bold;"><big> |
| 6 | HBase 範例 |
| 7 | </big></big></div> |
| 8 | }}} |
| 9 | |
| 10 | [wiki:waue/2011/0426_4 上一關 < ] 第二關 [wiki:waue/2011/0426_4_3 > 下一關] |
| 11 | |
| 12 | = 範例二: Put 資料進 Column = |
| 13 | |
| 14 | * 注意: 若此程式執行於 eclipse ,則方便起見,請將程式的 eclipse only 的後兩行的註解取消 |
| 15 | * 之後的範例有同樣情況就不寫了 |
| 16 | |
| 17 | {{{ |
| 18 | $ bin/hadoop jar ItriMenu.jar PutData "ex1Table" "row221" "Detail" "c1" "my value good" |
| 19 | }}} |
| 20 | = putData.java = |
| 21 | |
| 22 | {{{ |
| 23 | #!java |
| 24 | |
| 25 | package itri; |
| 26 | |
| 27 | import java.io.IOException; |
| 28 | |
| 29 | import org.apache.hadoop.conf.Configuration; |
| 30 | import org.apache.hadoop.hbase.HBaseConfiguration; |
| 31 | import org.apache.hadoop.hbase.client.HTable; |
| 32 | import org.apache.hadoop.hbase.client.Put; |
| 33 | import org.apache.hadoop.hbase.util.Bytes; |
| 34 | import org.apache.hadoop.util.GenericOptionsParser; |
| 35 | |
| 36 | public class PutData { |
| 37 | public PutData(String tablename, String row, String family, String column, |
| 38 | String value) { |
| 39 | try { |
| 40 | putData(tablename, row, family, column, value); |
| 41 | } catch (IOException e) { |
| 42 | e.printStackTrace(); |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | static public void putData(String tablename, String row, String family, |
| 47 | String column, String value) throws IOException { |
| 48 | // HBaseConfiguration 能接收 hbase-site.xml 的設定值 |
| 49 | HBaseConfiguration config = new HBaseConfiguration(); |
| 50 | // 檔案的操作則使用 HBaseAdmin |
| 51 | HTable table = new HTable(config, tablename); |
| 52 | |
| 53 | byte[] brow = Bytes.toBytes(row); |
| 54 | byte[] bfamily = Bytes.toBytes(family); |
| 55 | byte[] bcolumn = Bytes.toBytes(column); |
| 56 | byte[] bvalue = Bytes.toBytes(value); |
| 57 | |
| 58 | Put p = new Put(brow); |
| 59 | p.add(bfamily, bcolumn, bvalue); |
| 60 | |
| 61 | table.put(p); |
| 62 | System.out.println("Put data :\"" + value + "\" to Table: " + tablename |
| 63 | + "'s " + family + ":" + column); |
| 64 | |
| 65 | table.close(); |
| 66 | } |
| 67 | |
| 68 | static public void main(String argv[]) throws IOException { |
| 69 | // String[] argc = {"t1","r1","f1","c1","v1"};argv = argc; |
| 70 | |
| 71 | String[] args = new GenericOptionsParser(new Configuration(), argv) |
| 72 | .getRemainingArgs(); |
| 73 | if (args.length < 5) { |
| 74 | System.out.println("PutData <TableName> <Row> <Family> <Qualifier> <Value>"); |
| 75 | return; |
| 76 | } |
| 77 | putData(args[0],args[1],args[2],args[3],args[4]); |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | }}} |
| 82 | |
| 83 | * 執行結果 |
| 84 | {{{ |
| 85 | Put data :"my value good" to Table: ex1Table's Detail:c1 |
| 86 | }}} |