以下是HBase Java API 插入数据的样例代码,包括使用Put类、Batch操作、HTableInterface类和HTable类:
1.Put类
// 创建HBase Configuration对象
Configuration conf = HBaseConfiguration.create();
// 获取HBase表连接
Connection connection = ConnectionFactory.createConnection(conf);
Table table = connection.getTable(TableName.valueOf("table_name"));
// 创建Put对象
Put put = new Put(Bytes.toBytes("row_key"));
// 添加列数据
put.addColumn(Bytes.toBytes("column_family"), Bytes.toBytes("column_name"), Bytes.toBytes("value"));
// 插入数据
table.put(put);
// 关闭连接
table.close();
connection.close();
2.Batch操作
// 创建HBase Configuration对象
Configuration conf = HBaseConfiguration.create();
// 获取HBase表连接
Connection connection = ConnectionFactory.createConnection(conf);
Table table = connection.getTable(TableName.valueOf("table_name"));
// 创建Put对象
Put put1 = new Put(Bytes.toBytes("row_key1"));
put1.addColumn(Bytes.toBytes("column_family"), Bytes.toBytes("column_name"), Bytes.toBytes("value1"));
Put put2 = new Put(Bytes.toBytes("row_key2"));
put2.addColumn(Bytes.toBytes("column_family"), Bytes.toBytes("column_name"), Bytes.toBytes("value2"));
// 创建Put列表
List<Put> puts = new ArrayList<Put>();
puts.add(put1);
puts.add(put2);
// 批量插入数据
table.put(puts);
// 关闭连接
table.close();
connection.close();
3.HTableInterface类
// 创建HBase Configuration对象
Configuration conf = HBaseConfiguration.create();
// 获取HBase表连接
Connection connection = ConnectionFactory.createConnection(conf);
HTableInterface table = connection.getTable("table_name");
// 创建Put对象
Put put = new Put(Bytes.toBytes("row_key"));
// 添加列数据
put.addColumn(Bytes.toBytes("column_family"), Bytes.toBytes("column_name"), Bytes.toBytes("value"));
// 插入数据
table.put(put);
// 关闭连接
table.close();
connection.close();
4.HTable类
// 创建HBase Configuration对象
Configuration conf = HBaseConfiguration.create();
// 获取HBase表连接
Connection connection = ConnectionFactory.createConnection(conf);
HTable table = new HTable(conf, "table_name");
// 创建Put对象
Put put = new Put(Bytes.toBytes("row_key"));
// 添加列数据
put.addColumn(Bytes.toBytes("column_family"), Bytes.toBytes("column_name"), Bytes.toBytes("value"));
// 插入数据
table.put(put);
// 关闭连接
table.close();
connection.close();