更新时间:2024-10-31 GMT+08:00
向HBase表中插入数据
功能简介
HBase是一个面向列的数据库,一行数据,可能对应多个列族,而一个列族又可以对应多个列。通常,写入数据的时候,需要指定要写入的列(含列族名称和列名称)。HBase通过HTable的put方法来Put数据,可以是一行数据也可以是数据集。
代码样例
以下代码片段在com.huawei.bigdata.hbase.examples包的“HBaseSample”类的testPut方法中。
public void testPut() { LOG.info("Entering testPut."); // Specify the column family name. byte[] familyName = Bytes.toBytes("info"); // Specify the column name. byte[][] qualifiers = { Bytes.toBytes("name"), Bytes.toBytes("gender"), Bytes.toBytes("age"), Bytes.toBytes("address") }; Table table = null; try { // Instantiate an HTable object. table = conn.getTable(tableName); List<Put> puts = new ArrayList<Put>(); // Instantiate a Put object. Put put = putData(familyName, qualifiers, Arrays.asList("012005000201", "Zhang San", "Male", "19", "Shenzhen, Guangdong")); puts.add(put); put = putData(familyName, qualifiers, Arrays.asList("012005000202", "Li Wanting", "Female", "23", "Shijiazhuang, Hebei")); puts.add(put); put = putData(familyName, qualifiers, Arrays.asList("012005000203", "Wang Ming", "Male", "26", "Ningbo, Zhejiang")); puts.add(put); put = putData(familyName, qualifiers, Arrays.asList("012005000204", "Li Gang", "Male", "18", "Xiangyang, Hubei")); puts.add(put); put = putData(familyName, qualifiers, Arrays.asList("012005000205", "Zhao Enru", "Female", "21", "Shangrao, Jiangxi")); puts.add(put); put = putData(familyName, qualifiers, Arrays.asList("012005000206", "Chen Long", "Male", "32", "Zhuzhou, Hunan")); puts.add(put); put = putData(familyName, qualifiers, Arrays.asList("012005000207", "Zhou Wei", "Female", "29", "Nanyang, Henan")); puts.add(put); put = putData(familyName, qualifiers, Arrays.asList("012005000208", "Yang Yiwen", "Female", "30", "Kaixian, Chongqing")); puts.add(put); put = putData(familyName, qualifiers, Arrays.asList("012005000209", "Xu Bing", "Male", "26", "Weinan, Shaanxi")); puts.add(put); put = putData(familyName, qualifiers, Arrays.asList("012005000210", "Xiao Kai", "Male", "25", "Dalian, Liaoning")); puts.add(put); // Submit a put request. table.put(puts); LOG.info("Put successfully."); } catch (IOException e) { LOG.error("Put failed ", e); } finally { if (table != null) { try { // Close the HTable object. table.close(); } catch (IOException e) { LOG.error("Close table failed ", e); } } } LOG.info("Exiting testPut."); }
注意事项
不允许多个线程在同一时间共用同一个HTable实例。HTable是一个非线程安全类,因此,同一个HTable实例,不应该被多个线程同时使用,否则可能会带来并发问题。
父主题: HBase数据读写样例程序