1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
|
public class DataUtil { public static Table getTable(Connection conn, String tableName, String nsname) throws IOException { TableName tn = TableUtil.checkTableName(tableName, nsname); if (tn == null) { return null; } return conn.getTable(tn); } public static void put(Connection conn,String tableName,String nsname,String rowkey,String cloumnFamily, String cloumnQualifier,String value) throws IOException { Table table = getTable(conn, tableName, nsname); if (table==null) { return; } Put put = new Put(Bytes.toBytes(rowkey)); put.addColumn(Bytes.toBytes(cloumnFamily), Bytes.toBytes(cloumnQualifier), Bytes.toBytes(value)); table.put(put); table.close(); } public static void get(Connection conn,String tableName,String nsname,String rowkey) throws IOException { Table table = getTable(conn, tableName, nsname); if (table==null) { return ; } Get get = new Get(Bytes.toBytes(rowkey)); Result result = table.get(get); parseResult(result); table.close(); } public static void parseResult(Result result) { if (result != null) { Cell[] cells = result.rawCells(); for (Cell cell : cells) { System.out.println("行:"+ Bytes.toString(CellUtil.cloneRow(cell))+ " 列族:"+Bytes.toString(CellUtil.cloneFamily(cell))+" 列名:"+ Bytes.toString(CellUtil.cloneQualifier(cell))+ " 值:"+Bytes.toString(CellUtil.cloneValue(cell))); } } } public static void scan(Connection conn, String tableName, String nsname) throws Exception { Table table = getTable(conn, tableName, nsname);
if (table == null) { return; }
Scan scan = new Scan(); scan.withStartRow(Bytes.toBytes(1)); scan.withStopRow(Bytes.toBytes(50));
ResultScanner scanner = table.getScanner(scan);
Iterator<Result> iterator = scanner.iterator(); while (iterator.hasNext()) { Result next = iterator.next(); parseResult(next);
} table.close(); }
public static void delete(Connection conn, String tableName, String nsname, String rowKey) throws Exception { Table table = getTable(conn, tableName, nsname);
if (table == null) { return; }
Delete delete = new Delete(Bytes.toBytes(rowKey));
table.delete(delete); table.close(); } }
|