Use the JDBC driver for BigQuery

Preview

This feature is subject to the "Pre-GA Offerings Terms" in the General Service Terms section of theService Specific Terms. Pre-GA features are available "as is" and might have limited support. For more information, see thelaunch stage descriptions.

Note: To request feedback or support for this feature, send an email tobigquery-drivers-feedback@google.com.

The Java Database Connectivity (JDBC) driver for BigQuery connects yourJava applications to BigQuery, letting you useBigQuery features with your preferred tooling and infrastructure.To connect non-Java applications to BigQuery, use theSimba Open Database Connectivity (ODBC) driver for BigQuery.

Limitations

The JDBC driver for BigQuery is subject to the followinglimitations:

Before you begin

  1. Make sure that you're familiar with JDBC drivers, Apache Maven, andthejava.sql package.
  2. Verify that your system is configured with Java Runtime Environment (JRE)8.0 or later. For information on checking your JRE version, seeVerifying the JRE Environment.
  3. Authenticate to BigQuery,and take note of the following information, which is used later when youestablish a connection with the JDBC driver for BigQuery. Youonly need to note the information that corresponds to the authenticationmethod that you use.

    Authentication methodAuthentication informationExampleConnection property (to set later)
    Standard service accountService account emailbq-jdbc-sa@mytestproject.iam.gserviceaccount.comOAuthServiceAcctEmail
    Service account key (JSON object)my-sa-keyOAuthPvtKey
    Service account key fileService account key file (full path)path/to/file/secret.jsonOAuthPvtKeyPath
    Google user accountClient ID123-abc.apps.googleusercontent.comOAuthClientId
    Client secret_aB-C1D_E2fGh3Ij4kL5m6No7p8QR9sT0uVOAuthClientSecret
    Pre-generated access tokenAccess tokenya29.a0AfH6SMCiH1L-x_yZOAuthAccessToken
    Pre-generated refresh tokenRefresh token1/fFAGRNJru1FTz70BzhT3ZgOAuthRefreshToken
    Client ID123-abc.apps.googleusercontent.comOAuthClientId
    Client secret_aB-C1D_E2fGh3Ij4kL5m6No7p8QR9sT0uVOAuthClientSecret
    Application Default CredentialsNoneN/AN/A
    Configuration fileConfiguration file (JSON object or full path)path/to/file/secret.jsonOAuthPvtKey
    External account configuration objectAccount configuration objectexternal_account_configuration_objectOAuthPvtKey
    OtherAudience property of the external account configuration file//iam.googleapis.com/projects/my-project/locations/US-EAST1/workloadIdentityPools/my-pool-/providers/my-providerBYOID_AudienceUri
    Token retrieval and environmental information file{\"file\":\"/path/to/file\"}BYOID_CredentialSource
    User project (only if using a workforce pool)my_projectBYOID_PoolUserProject
    URI for service account impersonation (only if using a workforce pool)my-saBYOID_SA_Impersonation_Uri
    Security Token Service token based on the token exchange specificationurn:ietf:params:oauth:tokentype:id_tokenBYOID_SubjectTokenType
    Security Token Service token exchange endpointhttps://sts.googleapis.com/v1/tokenBYOID_TokenUri

Configure your development environment

To configure your development environment with the JDBC driver forBigQuery, do the following:

  1. Download one of the following JDBC packages:

  2. Add the downloaded JAR file to your classpath so that the Java compiler andruntime can locate the necessary JDBC classes. For information on adding afile to your classpath, seeSetting the Classpath.

  3. Add the following dependency to yourbuild file:

    <dependency><groupId>com.google.cloud</groupId><artifactId>google-cloud-bigquery-jdbc</artifactId><version>0.0.1</version><scope>system</scope><systemPath>path/to/file/google-jdbc-jar-with-dependencies.jar</systemPath></dependency>
  4. If you're using a Gradle project, add the following to your build file:

    dependencies{// ... other dependenciesimplementationfiles('path/to/file/google-jdbc-jar-with-dependencies.jar')}

Establish a connection

To establish a connection between your Java application andBigQuery with the JDBC driver for BigQuery, dothe following:

  1. Identify your connection string for the JDBC driver forBigQuery. This string captures all the required informationto establish a connection between your Java application andBigQuery. The connection string has the following format:

    jdbc:bigquery://HOST:PORT;ProjectId=PROJECT_ID;OAuthType=AUTH_TYPE;AUTH_PROPS;OTHER_PROPS

    Replace the following:

    • HOST: the DNS or IP address of the server.
    • PORT: the TCP port number.
    • PROJECT_ID: the ID of your BigQueryproject.
    • AUTH_TYPE: a number specifying the type ofauthentication that you used. One of the following:
      • 0: for service account authentication (standard and key file)
      • 1: for Google user account authentication
      • 2: for pre-generated refresh or access token authentication
      • 3: for Application Default Credential authentication
      • 4: for other authentication methods
    • AUTH_PROPS: the authentication information thatyou noted when youauthenticated to BigQuery, listed intheproperty_1=value_1; property_2=value_2;... format—for example,OAuthPvtKeyPath=path/to/file/secret.json, if you authenticated witha service account key file.
    • OTHER_PROPS (optional): additional connectionproperties for the JDBC driver, listed in theproperty_1=value_1; property_2=value_2;... format. For a full list ofconnection properties, seeConnection properties.
  2. Connect your Java application to the JDBC driver forBigQuery with either theDriverManagerorDataSourceclass.

    • Connect with theDriverManager class:

      importjava.sql.Connection;importjava.sql.DriverManager;privatestaticConnectiongetJdbcConnectionDM(){Connectionconnection=DriverManager.getConnection(CONNECTION_STRING);returnconnection;}

      ReplaceCONNECTION_STRING with the connectionstring from the previous step.

    • Connect with theDataSource class:

      importcom.google.cloud.bigquery.jdbc.DataSource;importjava.sql.Connection;importjava.sql.SQLException;privatestaticpublicConnectiongetJdbcConnectionDS()throwsSQLException{Connectionconnection=null;DataSourcedataSource=newcom.google.cloud.bigquery.jdbc.DataSource();dataSource.setURL(CONNECTION_STRING);connection=dataSource.getConnection();returnconnection;}

      ReplaceCONNECTION_STRING with the connectionstring from the previous step.

      TheDataSource class also has setter methods that you can use to setconnection properties, rather than includingthem in the connection string. The following is an example:

      privatestaticConnectiongetConnection()throwsSQLException{DataSourceds=newDataSource();ds.setURL(jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;);ds.setAuthType(3);// Application Default Credentialsds.setProjectId("MyTestProject");ds.setEnableHighThroughputAPI(true);ds.setLogLevel("6");ds.setUseQueryCache(false);returnds.getConnection();}

Connection properties

JDBC driver connection properties are configuration parameters that you includein the connection string or pass through setter methods when youestablish a connection to a database. The followingconnection properties are supported by the JDBC driver forBigQuery.

Note: All connection property names are case-insensitive. Boolean connectionproperties accept bothTRUE/FALSE and1/0.
Connection propertyDescriptionDefault valueData typeRequired
AdditionalProjects Projects that the driver can access for queries and metadata operations, in addition to the primary project set by theProjectId property.N/AComma-separated stringNo
AllowLargeResults Determines if the driver processes query results that are larger than 128 MB when theQueryDialect property is set toBIG_QUERY. If theQueryDialect property is set toSQL, the driver always processes large query results.TRUEBooleanNo
BYOID_AudienceUri The audience property in an external account configuration file. The audience property can contain the resource name for the workload identity pool or workforce pool, as well as the provider identifier in that pool.N/AStringOnly whenOAuthType=4
BYOID_CredentialSource The token retrieval and environmental information.N/AStringOnly whenOAuthType=4
BYOID_PoolUserProject The user project when a workforce pool is being used for authentication.N/AStringOnly whenOAuthType=4 and using the workforce pool
BYOID_SA_Impersonation_Uri The URI for the service account impersonation when a workforce pool is being used for authentication.N/AStringOnly whenOAuthType=4 and using the workforce pool
BYOID_SubjectTokenType The Security Token Service token based on the token exchange specification. One of the following:
  • urn:ietf:params:oauth:token-type:jwt
  • urn:ietf:params:oauth:token-type:id_token
  • urn:ietf:params:oauth:token-type:saml2
  • urn:ietf:params:aws:token-type:aws4_request
urn:ietf:params:oauth:tokentype:id_tokenStringOnly whenOAuthType=4
BYOID_TokenUri The Security Token Service token exchange endpoint.https://sts.googleapis.com/v1/tokenStringNo
ConnectionPoolSize The connection pool size, if connection pooling is enabled.10LongNo
DefaultDataset The dataset that's used when one isn't specified in a query.N/AStringNo
EnableHighThroughputAPI Determines if the Storage Read API can be used. TheHighThroughputActivationRatio andHighThroughputMinTableSize properties must also be set toTRUE to use the Storage Read API.FALSEBooleanNo
EnableSession Determines if the connection starts a session. If set toTRUE, the session ID is passed to all subsequent queries.FALSEBooleanNo
EnableWriteAPI Determines if the Storage Write API can be used. It must be set toTRUE to enable bulk inserts.FALSEBooleanNo
EndpointOverrides Custom endpoints to overwrite the following:
  • BIGQUERY=https://bigquery.googleapis.com
  • READ_API=https://bigquerystorage.googleapis.com
  • OAUTH2=https://oauth2.googleapis.com
  • STS=https://sts.googleapis.com
N/AComma-separated stringNo
FilterTablesOnDefaultDataset Determines the scope of metadata returned by theDatabaseMetaData.getTables() andDatabaseMetaData.getColumns() methods. When set toFALSE, no filtering occurs. TheDefaultDataset property must also be set to enable filtering.FALSEBooleanNo
HighThroughputActivationRatio The threshold for the number of pages in a query response. When this number is exceeded, and theEnableHighThroughputAPI andHighThroughputMinTableSize conditions are met, the driver starts using the Storage Read API.2IntegerNo
HighThroughputMinTableSize The threshold for the number of rows in a query response. When this number is exceeded, and theEnableHighThroughputAPI andHighThroughputActivationRatio conditions are met, the driver starts using the Storage Read API.100IntegerNo
JobCreationMode Determines if queries are run with or without jobs. A1 value means that jobs are created for every query, and a2 value means that queries can be executed without jobs.2IntegerNo
JobTimeout The job timeout (in seconds) after which the job is cancelled on the server.0LongNo
KMSKeyName The KMS key name for encrypting data.N/AStringNo
Labels Labels that are associated with the query to organize and group query jobs.N/AMap<String, String>No
LargeResultDataset The destination dataset for large query results, only when theLargeResultTable property is set. When you set this property, data writes bypass the result cache and trigger billing for each query, even if the results are small._google_jdbcStringNo
LargeResultsDatasetExpirationTime The lifetime of all tables in a large result dataset, in milliseconds. This property is ignored if the dataset already has a default expiration time set.3600000LongNo
LargeResultTable The destination table for large query results, only when theLargeResultDataset property is set. When you set this property, data writes bypass the result cache and trigger billing for each query, even if the results are small.temp_table...StringNo
ListenerPoolSize The listener pool size, if connection pooling is enabled.10LongNo
Location Thelocation where datasets are created or queried. BigQuery automatically determines the location if this property isn't set.N/AStringNo
LogLevel The level of detail logged by thejava.util.logging package during database interactions. Logging can affect performance, so only enable it temporarily to capture an issue. One of the following:
  • 0: theOFF level
  • 1: theSEVERE level
  • 2: theWARNING level
  • 3: theINFO level
  • 4: theCONFIG level
  • 5: theFINE level
  • 6: theFINER level
  • 7: theFINEST level
  • 8: theALL level
0IntegerNo
LogPath The directory where log files are written.N/AStringNo
MaximumBytesBilled The limit of bytes billed. Queries with bytes billed greater than this number fail without incurring a charge.0LongNo
MaxResults The maximum number of results per page.10000LongNo
MetaDataFetchThreadCount The number of threads used for database metadata methods.32IntegerNo
OAuthAccessToken The access token that's used for pre-generated access token authentication.N/AStringOnly whenOAUTH_TYPE=2
OAuthClientId The client ID for pre-generated refresh token authentication and user account authentication.N/AStringOnly whenOAUTH_TYPE=1 orOAUTH_TYPE=2
OAuthClientSecret The client secret for pre-generated refresh token authentication and user account authentication.N/AStringOnly whenOAUTH_TYPE=1 orOAUTH_TYPE=2
OAuthP12Password The password for the PKCS12 key file.notasecretStringNo
OAuthPvtKey The service account key when using service account authentication. This value can be a raw JSON keyfile object or a path to the JSON keyfile.N/AString Only whenOAUTH_TYPE=0 and theOAuthPvtKeyPath value isn't set
OAuthPvtKeyPath The path to the service account key when using service account authentication.N/AString Only whenOAUTH_TYPE=0 and theOAuthPvtKey andOAuthServiceAcctEmail values aren't set
OAuthRefreshToken The refresh token for pre-generated refresh token authentication.N/AString Only whenOAUTH_TYPE=2
OAuthServiceAcctEmail The service account email when using service account authentication.N/AString Only whenOAUTH_TYPE=0 and theOAuthPvtKeyPath value isn't set
OAuthType The authentication type. One of the following:
  • 0: service account authentication
  • 1: user account authentication
  • 2: pre-generated refresh or access token authentication
  • 3: Application Default Credential authentication
  • 4: other authentication methods
-1IntegerYes
PartnerToken A token that's used by Google Cloud partners to track usage of the driver.N/AStringNo
ProjectId The default project ID for the driver. This project is used to execute queries and is billed for resource usage. If not set, the driver infers a project ID.N/AStringNo, but highly recommended
ProxyHost The hostname or IP address of a proxy server through which the JDBC connection is routed.N/AStringNo
ProxyPort The port number on which the proxy server is listening for connections.N/AStringNo
ProxyPwd The password for authentication when connecting through a proxy server that requires it.N/AStringNo
ProxyUid The username for authentication when connecting through a proxy server that requires it.N/AStringNo
QueryDialect The SQL dialect for query execution. UseSQL for GoogleSQL (highly recommended) andBIG_QUERY for legacy SQL.SQLStringNo
QueryPropertiesREST connection properties that customize query behavior.N/AMap<String, String>No
RequestGoogleDriveScope Adds read-only Drive scope to the connection when set to1.0IntegerNo
RetryInitialDelay Sets the delay (in seconds) before the first retry.0LongNo
RetryMaxDelay Sets the maximum limit (in seconds) for the retry delay.0LongNo
ServiceAccountImpersonationChain A comma-separated list of service account emails in the impersonation chain.N/AStringNo
ServiceAccountImpersonationEmail The service account email to be impersonated.N/AStringNo
ServiceAccountImpersonationScopes A comma-separated list of OAuth2 scopes to use with the impersonated account.https://www.googleapis.com/auth/bigqueryStringNo
ServiceAccountImpersonationTokenLifetime The impersonated account token lifetime (in seconds).3600IntegerNo
SSLTrustStore The full path to the Java TrustStore that contains trusted Certificate Authority (CA) certificates. The driver utilizes this truststore to validate the identity of the server during the SSL/TLS handshake.N/AStringNo
SSLTrustStorePwd The password to the Java TrustStore specified in theSSLTrustStore property.N/AStringOnly if the Java TrustStore is password-protected
SWA_ActivationRowCount The threshold ofexecuteBatch insert rows which, when exceeded, causes the connector to switch to the Storage Write API.3IntegerNo
SWA_AppendRowCount The size of the write stream.1000IntegerNo
Timeout The length of time, in seconds, that the connector retries a failed API call before timing out.0LongNo
UniverseDomain The top-level domain that's associated with your organization's Google Cloud resources.googleapis.comStringNo
UnsupportedHTAPIFallback Determines if the connector falls back to the REST API (when set toTRUE) or returns an error (when set toFALSE).TRUEBooleanNo
UseQueryCache Enables query caching.TRUEBooleanNo

Run queries with the driver

With your Java application connected to BigQuery through theJDBC driver, you can now run queries in your development environment through thestandard JDBC process.AllBigQuery quotas and limits apply.

Data type mapping

When you run queries through the JDBC driver for BigQuery, thefollowing data type mapping occurs:

GoogleSQL typeJava type
ARRAYArray
BIGNUMERICBigDecimal
BOOLBoolean
BYTESbyte[]
DATEDate
DATETIMEString
FLOAT64Double
GEOGRAPHYString
INT64Long
INTERVALString
JSONString
NUMERICBigDecimal
STRINGString
STRUCTStruct
TIMETime
TIMESTAMPTimestamp

Examples

The following sections provide examples that use BigQueryfeatures through the JDBC driver for BigQuery.

Positional parameters

The following example runs a query with apositional parameter:

PreparedStatementpreparedStatement=connection.prepareStatement("SELECT * FROM MyTestTable where testColumn = ?");preparedStatement.setString(1,"string2");ResultSetresultSet=statement.executeQuery(selectQuery);

Nested and repeated records

The following example queries the base record ofStruct data:

ResultSetresultSet=statement.executeQuery("SELECT STRUCT(\"Adam\" as name, 5 as age)");resultSet.next();Structobj=(Struct)resultSet.getObject(1);System.out.println(obj.toString());

The driver returns the base record as a struct object or a stringrepresentation of a JSON object. The result is similar to the following:

{  "v": {    "f": [      {        "v": "Adam"      },      {        "v": "5"      }    ]  }}

The following example queries the subcomponents of aStruct object:

ResultSetresultSet=statement.executeQuery("SELECT STRUCT(\"Adam\" as name, 5 as age)");resultSet.next();StructstructObject=(Struct)resultSet.getObject(1);Object[]structComponents=structObject.getAttributes();for(Objectcomponent:structComponents){System.out.println(component.toString());}

The following example queries a standard array of repeated data, then verifiesthe result:

// Execute QueryResultSetresultSet=statement.executeQuery("SELECT [1,2,3]");resultSet.next();Object[]arrayObject=(Object[])resultSet.getArray(1).getArray();// Verify Resultintcount=0;for(;count<arrayObject.length;count++){System.out.println(arrayObject[count]);}

The following example queries aStruct array of repeated data, then verifiesthe result:

// Execute QueryResultSetresultSet=statement.executeQuery("SELECT "+"[STRUCT(\"Adam\" as name, 12 as age), "+"STRUCT(\"Lily\" as name, 17 as age)]");Struct[]arrayObject=(Struct[])resultSet.getArray(1).getArray();// Verify Resultfor(intcount=0;count<arrayObject.length;count++){System.out.println(arrayObject[count]);}

Bulk-insert

The following example performs a bulk-insert operation with theexecuteBatch method.

Connectionconn=DriverManager.getConnection(connectionUrl);PreparedStatementstatement=null;Statementst=conn.createStatement();finalStringinsertQuery=String.format("INSERT INTO `%s.%s.%s` "+" (StringField, IntegerField, BooleanField) VALUES(?, ?, ?);",DEFAULT_CATALOG,DATASET,TABLE_NAME);statement=conn.prepareStatement(insertQuery1);for(inti=0;i<2000;++i){statement.setString(1,i+"StringField");statement.setInt(2,i);statement.setBoolean(3,true);statement.addBatch();}statement.executeBatch();

Pricing

You can download the JDBC driver for BigQuery at no cost, and youdon't need any additional licenses to use the drivers. However, when you use thedriver,standard BigQuery pricingapplies.

What's next

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2026-02-18 UTC.