| 1 | {{{ |
| 2 | #!html |
| 3 | <div style="text-align: center; color:#151B8D"><big style="font-weight: bold;"><big><big> |
| 4 | HBase 進階課程 |
| 5 | </big></big></big></div> <div style="text-align: center; color:#7E2217"><big style="font-weight: bold;"><big> |
| 6 | 程式範例練習 |
| 7 | </big></big></div> |
| 8 | }}} |
| 9 | |
| 10 | [wiki:NCHCCloudCourse100929_4_HBEX 上一關 < ] 第二關 [wiki:NCHCCloudCourse100929_4_HBEX3 > 下一關] |
| 11 | |
| 12 | = 範例二: Put 資料進 Column = |
| 13 | |
| 14 | {{{ |
| 15 | #!java |
| 16 | package org.nchc.hbase; |
| 17 | |
| 18 | import java.io.IOException; |
| 19 | |
| 20 | import org.apache.hadoop.conf.Configuration; |
| 21 | import org.apache.hadoop.hbase.HBaseConfiguration; |
| 22 | import org.apache.hadoop.hbase.client.HTable; |
| 23 | import org.apache.hadoop.hbase.client.Put; |
| 24 | import org.apache.hadoop.hbase.util.Bytes; |
| 25 | import org.apache.hadoop.util.GenericOptionsParser; |
| 26 | |
| 27 | public class PutData { |
| 28 | public PutData(String tablename, String row, String family, String column, |
| 29 | String value) { |
| 30 | try { |
| 31 | putData(tablename, row, family, column, value); |
| 32 | } catch (IOException e) { |
| 33 | e.printStackTrace(); |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | static public void putData(String tablename, String row, String family, |
| 38 | String column, String value) throws IOException { |
| 39 | // HBaseConfiguration 能接收 hbase-site.xml 的設定值 |
| 40 | HBaseConfiguration config = new HBaseConfiguration(); |
| 41 | // 檔案的操作則使用 HBaseAdmin |
| 42 | HTable table = new HTable(config, tablename); |
| 43 | |
| 44 | byte[] brow = Bytes.toBytes(row); |
| 45 | byte[] bfamily = Bytes.toBytes(family); |
| 46 | byte[] bcolumn = Bytes.toBytes(column); |
| 47 | byte[] bvalue = Bytes.toBytes(value); |
| 48 | |
| 49 | Put p = new Put(brow); |
| 50 | p.add(bfamily, bcolumn, bvalue); |
| 51 | |
| 52 | table.put(p); |
| 53 | System.out.println("Put data :\"" + value + "\" to Table: " + tablename |
| 54 | + "'s " + family + ":" + column); |
| 55 | |
| 56 | table.close(); |
| 57 | } |
| 58 | |
| 59 | static public void main(String argv[]) throws IOException { |
| 60 | |
| 61 | String[] args = new GenericOptionsParser(new Configuration(), argv) |
| 62 | .getRemainingArgs(); |
| 63 | if (args.length < 5) { |
| 64 | System.out.println("PutData <TableName> <Row> <Family> <Qualifier> <Value>"); |
| 65 | return; |
| 66 | } |
| 67 | putData(args[0],args[1],args[2],args[3],args[4]); |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | }}} |