# Connect with the JDBC driver

You can use the Bigtable Java Database Connectivity (JDBC) driver to
connect the following applications to Bigtable:

- [Java applications](https://docs.cloud.google.com/bigtable/docs/reference/jdbc#connect-from-java) that use the JDBC API.
- [Tools and frameworks that support JDBC connections](https://docs.cloud.google.com/bigtable/docs/reference/jdbc#connect-from-tool-framework), such as business intelligence tools and Extract, Transform, and Load (ETL) frameworks.

The Bigtable JDBC driver is a wrapper around the
Bigtable client for Java that lets you run queries on your
Bigtable data using GoogleSQL.

Bigtable provides the JDBC driver (`google-cloud-bigtable-jdbc`)
as a JAR file that you can download from the [Maven repository](https://repo1.maven.org/maven2/com/google/cloud/google-cloud-bigtable-jdbc/)
or integrate directly into your Java-based projects.

## Limitations

The following limitations apply when you use the Bigtable JDBC
driver:

- GoogleSQL for Bigtable limitations apply. For more information, see [Use cases](https://docs.cloud.google.com/bigtable/docs/googlesql-overview#use-cases).
- In queries with parameters, changing a parameter type results in an error.
- The driver doesn't support connection pooling. We recommend that you reuse a single connection for all queries.

## Required roles

To get the permissions that you need to run queries using the
Bigtable JDBC driver, ask your administrator to grant you the
Bigtable Reader
([`roles/bigtable.reader`](https://docs.cloud.google.com/bigtable/docs/access-control#bigtable.reader))
Identity and Access Management (IAM) role on your project. This read-only role is
sufficient for applications that only query data.

For more information about granting roles, see
[Manage access to projects, folders, and organizations](https://docs.cloud.google.com/iam/docs/granting-changing-revoking-access).

## Before you begin

To complete the following example, install Java JDK version 8 or later and
[Apache Maven](https://maven.apache.org/install.html).

## Connect from a Java application

To use the Bigtable JDBC driver to connect a Java application to
Bigtable, complete the following steps:

1. **Add the [Bigtable JDBC driver](https://repo1.maven.org/maven2/com/google/cloud/google-cloud-bigtable-jdbc/) to your
   application.** Declare the driver as a dependency by adding code that is
   similar to the following to the Maven `pom.xml` file of your project:

       <!-- pom.xml in the `dependencies` element -->
       <dependency>
           <groupId>com.google.cloud</groupId>
           <artifactId>google-cloud-bigtable-jdbc</artifactId>
           <version>1.0.0</version>
       </dependency>

2. Load the driver class by including the following command in the startup
   sequence of your application:

       public static void main(String[] args) {
            // Step 1: Load the Bigtable JDBC driver class at runtime
            try {
                Class.forName("com.google.cloud.bigtable.jdbc.BigtableDriver");
                System.out.println("Bigtable JDBC Driver loaded successfully.");
            } catch (ClassNotFoundException e) {
                System.err.println("Could not load Bigtable JDBC Driver. Make sure the JAR is on the classpath.");
                throw new RuntimeException(e);
            }

3. Build a Java project in Apache Maven.

4. Create the connection URL by using one of the following authentication
   methods:

   - **Application Default Credentials (ADC)**: when you don't provide credentials, the driver uses ADC by default.
   - **Service account JSON key file** : provide the local path to a service account JSON key file using the `credential_file_path` property.
   - **Service account JSON string** : provide the full JSON content of a service account key directly in the connection string using the `credential_json` property.

   > [!NOTE]
   > **Note:** If you provide multiple methods, `credential_json` takes highest precedence, followed by `credential_file_path`, then ADC.

       // Step 2: Set up the connection string

       // Use Application Default Credentials (ADC):
       String connStr = "jdbc:bigtable:/projects/PROJECT_NAME"
           + "/instances/INSTANCE_NAME?app_profile_id=APP_PROFILE"
           + "&universe_domain=UNIVERSE_DOMAIN";

       // OR authenticate using a service account JSON key file:
       // String connStr = "jdbc:bigtable:/projects/PROJECT_NAME"
       //     + "/instances/INSTANCE_NAME?credential_file_path=PATH_TO_KEY_FILE"
       //     + "&universe_domain=UNIVERSE_DOMAIN";

       // OR authenticate using the contents of a JSON file:
       // String connStr = "jdbc:bigtable:/projects/PROJECT_NAME"
       //     + "/instances/INSTANCE_NAME"?credential_json=CREDENTIAL_JSON_STRING"
       //     + "&universe_domain=UNIVERSE_DOMAIN";

       // Step 3: Now you can establish a connection
         try (Connection connection = DriverManager.getConnection(connStr)) {
             System.out.println("Connection to Bigtable established: " + !connection.isClosed());
             // You can now execute queries using this connection object
         } catch (SQLException e) {
             System.err.println("Failed to connect to Bigtable.");
             throw new RuntimeException(e);
         }

   Replace the following:
   - `PROJECT_NAME`: the name of the project where your Bigtable instance is located
   - `INSTANCE_NAME`: the name of your Bigtable instance
   - Optional: `APP_PROFILE`: the name of the specific application profile that you want to use for the connection.
   - Optional: `CREDENTIAL_JSON_STRING`: the full JSON content of your service account key.
   - Optional: `PATH_TO_KEY_FILE`: the full path to your service account JSON key file.
   - Optional: `UNIVERSE_DOMAIN`: if your universe is other than the default Google Cloud, the universe domain for the connection endpoint.
5. Run queries. For query examples, see the
   [Sample queries](https://docs.cloud.google.com/bigtable/docs/reference/jdbc#sample-queries) section of this document.

6. Process a result. For a sample result, see the
   [Process a result](https://docs.cloud.google.com/bigtable/docs/reference/jdbc#process-result) section of this document.

### Sample queries

You can query your Bigtable data using standard JDBC interfaces
defined in the JDBC API. For more information about how to write
Bigtable queries, see
[GoogleSQL for Bigtable overview](https://docs.cloud.google.com/bigtable/docs/googlesql-overview).

#### One-time queries

Use statement objects to run one-time queries, as shown in the following example:

       try (Connection connection = DriverManager.getConnection(connStr)) {
         try (Statement statement = connection.createStatement()) {
           try (ResultSet rs = statement.executeQuery("SELECT _key, columnFamily['qualifier'] FROM myTable WHERE _key = 'first-row'")) {
             while (rs.next()) {
               // Process query results
             }
           }
         }
       } catch (SQLException e) {
         throw new RuntimeException(e);
       }

#### Queries with parameters

For queries that you run multiple times with different parameters, use a
[PreparedStatement](https://docs.oracle.com/javase/8/docs/api/java/sql/PreparedStatement.html)
for better efficiency, as shown in the following example:

    try (Connection connection = DriverManager.getConnection(connStr)) {
      // Note that JDBC uses positional parameters, as opposed to Google SQL for Bigtable which uses named parameters.
      try (PreparedStatement statement = connection.prepareStatement("SELECT _key, columnFamily['qualifier'] FROM myTable WHERE _key = ?")) {
        // Reuse the prepared statement for multiple queries
        for (String param : new String[]{"row1", "row2"}) {
          statement.setString(1, param);
          try (ResultSet rs = statement.executeQuery()) {
            while (rs.next()) {
              // Process query results
            }
          }
        }
      }
    } catch (SQLException e) {
      throw new RuntimeException(e);
    }

> [!NOTE]
> **Note:** If you set a parameter to a type, and then try to set it to a different type, you'll receive an error.

### Process a result

Bigtable returns query results as a
[ResultSet](https://docs.oracle.com/javase/8/docs/api/java/sql/ResultSet.html)
object, which is a standard JDBC interface that represents table data returned
from a query. By default, queries return fields as bytes or map types unless you
[cast](https://docs.cloud.google.com/bigtable/docs/reference/sql/conversion_functions#conversion_functions)
them to the appropriate type in your SQL statement or in a
[logical view](https://docs.cloud.google.com/bigtable/docs/create-manage-logical-views).

The following example shows how to iterate through each row of data in the
result set to access the data returned by the SQL query:

    try (ResultSet rs = statement.executeQuery()) {
      while (rs.next()) {
        System.out.printf(rs.getString(0));
      }
    }

## Connect from a tool or a framework

To use the Bigtable JDBC driver to connect a tool, such as a
business intelligence application, or an ETL framework to
Bigtable, follow these steps:

1. Download the [Bigtable JDBC driver](https://repo1.maven.org/maven2/com/google/cloud/google-cloud-bigtable-jdbc/). For more information about how to install and configure the driver, see the applicable vendor documentation.
2. Provide the JDBC connection string to configure a new connection within the tool's web interface.

## Support

[Cloud Customer Care](https://docs.cloud.google.com/bigtable/docs/support/getting-support) provides support for JDBC drivers.

## Pricing

You can download the Bigtable JDBC driver at no cost. However,
you're charged for the Bigtable resources that your queries use.

Costs for using the Bigtable JDBC driver vary depending on your
configuration:

- The nodes in your Bigtable cluster process queries that are sent through the JDBC driver. You're billed for the number of nodes in your cluster. Running queries consumes CPU, and we recommend that you monitor your cluster's CPU utilization to ensure that it's provisioned appropriately.
- You're billed for the amount of data stored in your Bigtable tables.
- You're billed for any data that the JDBC driver transfers from Bigtable to your client application over the network.

## What's next

- Explore the [Bigtable JDBC driver source code](https://github.com/GoogleCloudPlatform/java-bigtable-jdbc)
- [Schema design best practices](https://docs.cloud.google.com/bigtable/docs/schema-design)
- [Understand performance](https://docs.cloud.google.com/bigtable/docs/performance)