MAPREDUCE服务 MRS-读取Phoenix表数据:代码样例

时间:2024-06-29 14:10:57

代码样例

以下代码片段在com.huawei.bigdata.hbase.examples包的“PhoenixSample”类的testSelect方法中。

  /**
   * Select Data
   */
  public void testSelect() {
     LOG .info("Entering testSelect.");
    String URL = "jdbc:phoenix:" + conf.get("hbase.zookeeper.quorum");
    // Query
    String querySQL = "SELECT * FROM TEST WHERE id = ?";
    Connection conn = null;
    PreparedStatement preStat = null;
    Statement stat = null;
    ResultSet result = null;
    try {
      // Create Connection
      conn = DriverManager.getConnection(url, props);
      // Create Statement
      stat = conn.createStatement();
      // Create PrepareStatement
      preStat = conn.prepareStatement(querySQL);
      // Execute query
      preStat.setInt(1, 1);
      result = preStat.executeQuery();
      // Get result
      while (result.next()) {
        int id = result.getInt("id");
        String name = result.getString(1);
        System.out.println("id: " + id);
        System.out.println("name: " + name);
      }
      LOG.info("Select successfully.");
    } catch (Exception e) {
      LOG.error("Select failed.", e);
    } finally {
      if (null != result) {
        try {
          result.close();
        } catch (Exception e2) {
          LOG.error("Result close failed.", e2);
        }
      }
      if (null != stat) {
        try {
          stat.close();
        } catch (Exception e2) {
          LOG.error("Stat close failed.", e2);
        }
      }
      if (null != conn) {
        try {
          conn.close();
        } catch (Exception e2) {
          LOG.error("Connection close failed.", e2);
        }
      }
    }
    LOG.info("Exiting testSelect.");
  }
support.huaweicloud.com/devg3-mrs/mrs_07_080038.html