列出表格

列出 Cloud Bigtable 執行個體中的所有資料表。

深入探索

如需包含這個程式碼範例的詳細說明文件,請參閱下列文章:

程式碼範例

C++

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

namespace cbt = ::google::cloud::bigtable;
namespace cbta = ::google::cloud::bigtable_admin;
using ::google::cloud::StreamRange;
[](cbta::BigtableTableAdminClient admin, std::string const& project_id,
   std::string const& instance_id) {
  std::string instance_name = cbt::InstanceName(project_id, instance_id);

  google::bigtable::admin::v2::ListTablesRequest r;
  r.set_parent(instance_name);
  r.set_view(google::bigtable::admin::v2::Table::NAME_ONLY);

  StreamRange<google::bigtable::admin::v2::Table> tables =
      admin.ListTables(std::move(r));
  for (auto& table : tables) {
    if (!table) throw std::move(table).status();
    std::cout << table->name() << "\n";
  }
}

C#

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

// Lists tables in intance.
// Initialize request argument(s).
ListTablesRequest request = new ListTablesRequest
{
    ParentAsInstanceName = s_instanceName
};
try
{
    // Make the request.
    PagedEnumerable<ListTablesResponse, Table> response = bigtableTableAdminClient.ListTables(request);

}
catch (Exception ex)
{
    Console.WriteLine($"Error listing tables {ex.Message}");
}

Go

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


import (
	"context"
	"fmt"
	"io"

	bigtableadmin "cloud.google.com/go/bigtable/admin/apiv2"
	"cloud.google.com/go/bigtable/admin/apiv2/adminpb"
	"google.golang.org/api/iterator"
)

// listTables lists Cloud Bigtable tables within an instance.
func listTables(ctx context.Context, w io.Writer, projectID string, instanceID string) error {
	parent := fmt.Sprintf("projects/%s/instances/%s", projectID, instanceID)

	client, err := bigtableadmin.NewBigtableTableAdminClient(ctx)
	if err != nil {
		return fmt.Errorf("NewBigtableTableAdminClient: %w", err)
	}
	defer client.Close()

	req := &adminpb.ListTablesRequest{
		Parent: parent,
	}

	it := client.ListTables(ctx, req)
	for {
		table, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("Next: %w", err)
		}
		fmt.Fprintf(w, "Table: %s\n", table.GetName())
	}

	return nil
}

Java

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

// Lists tables in the current instance.
try {
  String parent = "projects/" + projectId + "/instances/" + instanceId;
  ListTablesRequest request = ListTablesRequest.newBuilder().setParent(parent).build();
  for (Table table : adminClient.listTables(request).iterateAll()) {
    System.out.println(table.getName());
  }
} catch (NotFoundException e) {
  System.err.println("Failed to list tables from a non-existent instance: " + e.getMessage());
}

Node.js

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

'use strict';

const {BigtableTableAdminClient} = require('@google-cloud/bigtable').v2;
const {status} = require('@grpc/grpc-js');

const client = new BigtableTableAdminClient();

/**
 * Lists the Cloud Bigtable tables in a specified instance.
 *
 * @param {string} projectId - The Google Cloud project ID (for example, 'example-project-id').
 * @param {string} instanceId - The Cloud Bigtable instance ID (for example, 'example-instance').
 */
async function listTables(projectId, instanceId) {
  try {
    const parent = `projects/${projectId}/instances/${instanceId}`;
    const [tables] = await client.listTables({parent});

    console.log(`Tables in instance ${instanceId}:`);
    for (const table of tables) {
      console.log(`Table: ${table.name}`);
    }
  } catch (err) {
    if (err.code === status.NOT_FOUND) {
      console.error(`Instance not found: ${err.message}`);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(`Permission denied: ${err.message}`);
    } else if (err.code !== undefined) {
      console.error(`Google API error (${err.code}): ${err.message}`);
    } else {
      throw err;
    }
  }
}

module.exports = {listTables};

PHP

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

use Google\Cloud\Bigtable\Admin\V2\Client\BigtableInstanceAdminClient;
use Google\Cloud\Bigtable\Admin\V2\Client\BigtableTableAdminClient;
use Google\Cloud\Bigtable\Admin\V2\ListTablesRequest;

/**
 * List tables in an instance
 *
 * @param string $projectId The Google Cloud project ID
 * @param string $instanceId The ID of the Bigtable instance
 */
function list_tables(
    string $projectId,
    string $instanceId
): void {
    $instanceAdminClient = new BigtableInstanceAdminClient();
    $tableAdminClient = new BigtableTableAdminClient();

    $instanceName = $instanceAdminClient->instanceName($projectId, $instanceId);

    printf('Listing Tables:' . PHP_EOL);
    $listTablesRequest = (new ListTablesRequest())
        ->setParent($instanceName);
    $tables = $tableAdminClient->listTables($listTablesRequest)->iterateAllElements();
    $tables = iterator_to_array($tables);
    if (empty($tables)) {
        print('No table exists.' . PHP_EOL);
        return;
    }
    foreach ($tables as $table) {
        print($table->getName() . PHP_EOL);
    }
}

Python

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

from google.api_core import exceptions
from google.api_core.client_options import ClientOptions
from google.cloud import bigtable_admin_v2


def list_tables(project_id: str, instance_id: str) -> None:
    """Lists tables in an instance using the list_tables method.

    Args:
        project_id: The Google Cloud project ID (for example, 'example-project-id').
        instance_id: ID of the Instance (for example, 'example-instance-id').
    """
    client_options = ClientOptions(quota_project_id=project_id)
    client = bigtable_admin_v2.BigtableTableAdminClient(
        client_options=client_options
    )
    parent = f"projects/{project_id}/instances/{instance_id}"

    try:
        response = client.list_tables(parent=parent)
        for table in response:
            print(f"Table name: {table.name}")
    except exceptions.GoogleAPICallError as error:
        print(f"API call failed: {error}")

Ruby

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

# instance_id = "my-instance"
bigtable.tables(instance_id).all.each do |t|
  puts "Table: #{t.name}"
end

後續步驟

如要搜尋及篩選其他 Google Cloud 產品的程式碼範例,請參閱Google Cloud 範例瀏覽工具。