连接hbase查找scofield的score:English成绩的Java代码
时间: 2024-11-27 10:23:21 浏览: 16
在HBase中查询某个学生Scofield的英语成绩(Score),通常需要通过HBase的Row Key进行访问,因为HBase是一种列族存储系统,数据是以行键-列族-列的形式组织的。假设我们有一个名为"students"的表,其中包含"student_id"作为row key,"english_score"作为列簇(Column Family)的一部分。
以下是一个简单的Java示例,使用HBase Java Client API来获取Scofield的英语成绩:
```java
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Scanner;
public class HBaseQuery {
private static final String COLUMN_FAMILY = "scores";
private static final byte[] SCOFIELD_ID = "Scofield".getBytes();
public static void main(String[] args) throws Exception {
// 创建HBase连接
Connection connection = ConnectionFactory.createConnection();
HBaseAdmin admin = new HBaseAdmin(connection);
// 确保表存在
if (!admin.tableExists("students")) {
System.out.println("Table 'students' not found");
return;
}
// 设置扫描器的row filter
Scan scan = new Scan();
scan.setStartRow(SCOFIELD_ID);
scan.setStopRow((byte[]) null); // 查询整个范围
// 扫描并获取结果
Scanner scanner = admin.getScanner("students", scan);
try {
while (scanner.next() != null) {
Result result = scanner.getCurrentResult();
byte[] englishScoreBytes = result.getValue(COLUMN_FAMILY, "english_score".getBytes());
double score = Bytes.toDouble(englishScoreBytes);
System.out.printf("Student Scofield's English Score is: %.2f%n", score);
}
} finally {
scanner.close(); // 关闭扫描器
}
admin.close(); // 关闭HBaseAdmin
connection.close(); // 关闭连接
}
}
```
阅读全文