Use the JDBC driver for BigQuery
The Java Database Connectivity (JDBC) driver for BigQuery connects your Java applications to BigQuery, letting you use BigQuery features with your preferred tooling and infrastructure. To connect non-Java applications to BigQuery, use the Simba Open Database Connectivity (ODBC) driver for BigQuery .
Limitations
The JDBC driver for BigQuery is subject to the following limitations:
- The driver is specific to BigQuery and can't be used with other products or services.
- The
INTERVALdata type isn't supported with the BigQuery Storage Read API. - All data manipulation language (DML) limitations apply.
Before you begin
- Make sure that you're familiar with JDBC drivers, Apache Maven, and
the
java.sqlpackage . - Verify that your system is configured with Java Runtime Environment (JRE) 8.0 or later. For information on checking your JRE version, see Verifying the JRE Environment .
-
Authenticate to BigQuery , and take note of the following information, which is used later when you establish a connection with the JDBC driver for BigQuery. You only need to note the information that corresponds to the authentication method that you use.
Authentication methodAuthentication informationExampleConnection property (to set later)Standard service accountService account emailbq-jdbc-sa@mytestproject.iam.gserviceaccount.comOAuthServiceAcctEmailService account key (JSON object)my-sa-keyOAuthPvtKeyService account key fileService account key file (full path)path/to/file/secret.jsonOAuthPvtKeyPathGoogle user accountClient ID123-abc.apps.googleusercontent.comOAuthClientIdClient secret_aB-C1D_E2fGh3Ij4kL5m6No7p8QR9sT0uVOAuthClientSecretPre-generated access tokenAccess tokenya29.a0AfH6SMCiH1L-x_yZOAuthAccessTokenPre-generated refresh tokenRefresh token1/fFAGRNJru1FTz70BzhT3ZgOAuthRefreshTokenClient ID123-abc.apps.googleusercontent.comOAuthClientIdClient secret_aB-C1D_E2fGh3Ij4kL5m6No7p8QR9sT0uVOAuthClientSecretApplication Default CredentialsNoneN/AN/AConfiguration fileConfiguration file (JSON object or full path)path/to/file/secret.jsonOAuthPvtKeyExternal account configuration objectAccount configuration objectexternal_account_configuration_objectOAuthPvtKeyOtherAudience property of the external account configuration file//iam.googleapis.com/projects/my-project/locations/US-EAST1/workloadIdentityPools/my-pool-/providers/my-providerBYOID_AudienceUriToken retrieval and environmental information file{\"file\":\"/path/to/file\"}BYOID_CredentialSourceUser project (only if using a workforce pool)my_projectBYOID_PoolUserProjectURI for service account impersonation (only if using a workforce pool)my-saBYOID_SA_Impersonation_UriSecurity Token Service token based on the token exchange specificationurn:ietf:params:oauth:tokentype:id_tokenBYOID_SubjectTokenTypeSecurity Token Service token exchange endpointhttps://sts.googleapis.com/v1/tokenBYOID_TokenUri
Configure your development environment
To configure your development environment with the JDBC driver for BigQuery, do the following:
-
Download one of the following JDBC packages:
- Uber JAR . A JAR file with all dependencies included.
- Shaded Uber JAR . A shaded JAR file with all dependencies included.
- Thin JAR with dependencies . A zip file that includes a thin JAR file and all dependencies.
-
Add the downloaded JAR file to your classpath so that the Java compiler and runtime can locate the necessary JDBC classes. For information on adding a file to your classpath, see Setting the Classpath .
-
Add the following dependency to your build 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 >
-
If you're using a Gradle project, add the following to your build file:
dependencies { // ... other dependencies implementation files ( ' path / to / file / google - jdbc - jar - with - dependencies . jar ' ) }
Establish a connection
To establish a connection between your Java application and BigQuery with the JDBC driver for BigQuery, do the following:
-
Identify your connection string for the JDBC driver for BigQuery. This string captures all the required information to establish a connection between your Java application and BigQuery. 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 BigQuery project. -
AUTH_TYPE: a number specifying the type of authentication 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 that you noted when you authenticated to BigQuery , listed in theproperty_1=value_1; property_2=value_2;...format—for example,OAuthPvtKeyPath=path/to/file/secret.json, if you authenticated with a service account key file. -
OTHER_PROPS(optional): additional connection properties for the JDBC driver, listed in theproperty_1=value_1; property_2=value_2;...format. For a full list of connection properties, see Connection properties .
-
-
Connect your Java application to the JDBC driver for BigQuery with either the
DriverManagerorDataSourceclass.-
Connect with the
DriverManagerclass:import java.sql.Connection ; import java.sql.DriverManager ; private static Connection getJdbcConnectionDM (){ Connection connection = DriverManager . getConnection ( CONNECTION_STRING ); return connection ; }
Replace
CONNECTION_STRINGwith the connection string from the previous step. -
Connect with the
DataSourceclass:import com.google.cloud.bigquery.jdbc. DataSource ; import java.sql.Connection ; import java.sql.SQLException ; private static public Connection getJdbcConnectionDS () throws SQLException { Connection connection = null ; DataSource dataSource = new com . google . cloud . bigquery . jdbc . DataSource (); dataSource . setURL ( CONNECTION_STRING ); connection = dataSource . getConnection (); return connection ; }
Replace
CONNECTION_STRINGwith the connection string from the previous step.The
DataSourceclass also has setter methods that you can use to set connection properties , rather than including them in the connection string. The following is an example:private static Connection getConnection () throws SQLException { DataSource ds = new DataSource (); ds . setURL ( jdbc : bigquery : //https://www.googleapis.com/bigquery/v2:443;); ds . setAuthType ( 3 ); // Application Default Credentials ds . setProjectId ( "MyTestProject" ); ds . setEnableHighThroughputAPI ( true ); ds . setLogLevel ( "6" ); ds . setUseQueryCache ( false ); return ds . getConnection (); }
-
Connection properties
JDBC driver connection properties are configuration parameters that you include in the connection string or pass through setter methods when you establish a connection to a database. The following connection properties are supported by the JDBC driver for BigQuery.
AdditionalProjects
ProjectId
property.AllowLargeResults
QueryDialect
property is set to BIG_QUERY
. If the QueryDialect
property is set
to SQL
, the driver always processes large query results.TRUE
BYOID_AudienceUri
OAuthType=4
BYOID_CredentialSource
OAuthType=4
BYOID_PoolUserProject
OAuthType=4
and using the workforce poolBYOID_SA_Impersonation_Uri
OAuthType=4
and using the workforce poolBYOID_SubjectTokenType
-
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_token
OAuthType=4
BYOID_TokenUri
https://sts.googleapis.com/v1/token
ConnectionPoolSize
10
DefaultDataset
EnableHighThroughputAPI
HighThroughputActivationRatio
and HighThroughputMinTableSize
properties must also be set to TRUE
to use the Storage Read API.FALSE
EnableSession
TRUE
, the session ID is passed to all subsequent queries.FALSE
EnableWriteAPI
TRUE
to enable bulk inserts.FALSE
EndpointOverrides
-
BIGQUERY=https://bigquery.googleapis.com -
READ_API=https://bigquerystorage.googleapis.com -
OAUTH2=https://oauth2.googleapis.com -
STS=https://sts.googleapis.com
FilterTablesOnDefaultDataset
DatabaseMetaData.getTables()
and DatabaseMetaData.getColumns()
methods. When set to FALSE
, no filtering occurs. The DefaultDataset
property must also be set to enable filtering.FALSE
HighThroughputActivationRatio
EnableHighThroughputAPI
and HighThroughputMinTableSize
conditions are met, the driver
starts using the Storage Read API.2
HighThroughputMinTableSize
EnableHighThroughputAPI
and HighThroughputActivationRatio
conditions are met, the driver
starts using the Storage Read API.100
JobCreationMode
1
value means that jobs are created for every query, and a 2
value means that queries can be executed without jobs.2
JobTimeout
0
KMSKeyName
Labels
LargeResultDataset
LargeResultTable
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_jdbc
LargeResultsDatasetExpirationTime
3600000
LargeResultTable
LargeResultDataset
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...
ListenerPoolSize
10
Location
LogLevel
java.util.logging
package
during database interactions. Logging can affect performance, so only
enable it temporarily to capture an issue. One of the following:-
0: theOFFlevel -
1: theSEVERElevel -
2: theWARNINGlevel -
3: theINFOlevel -
4: theCONFIGlevel -
5: theFINElevel -
6: theFINERlevel -
7: theFINESTlevel -
8: theALLlevel
0
LogPath
MaximumBytesBilled
0
MaxResults
10000
MetaDataFetchThreadCount
32
OAuthAccessToken
OAUTH_TYPE=2
OAuthClientId
OAUTH_TYPE=1
or OAUTH_TYPE=2
OAuthClientSecret
OAUTH_TYPE=1
or OAUTH_TYPE=2
OAuthP12Password
notasecret
OAuthPvtKey
OAUTH_TYPE=0
and the OAuthPvtKeyPath
value isn't setOAuthPvtKeyPath
OAUTH_TYPE=0
and the OAuthPvtKey
and OAuthServiceAcctEmail
values aren't setOAuthRefreshToken
OAUTH_TYPE=2
OAuthServiceAcctEmail
OAUTH_TYPE=0
and the OAuthPvtKeyPath
value isn't setOAuthType
-
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
-1
PartnerToken
ProjectId
ProxyHost
ProxyPort
ProxyPwd
ProxyUid
QueryDialect
SQL
for
GoogleSQL (highly recommended) and BIG_QUERY
for
legacy SQL.SQL
QueryProperties
RequestGoogleDriveScope
1
.0
RetryInitialDelay
0
RetryMaxDelay
0
ServiceAccountImpersonationChain
ServiceAccountImpersonationEmail
ServiceAccountImpersonationScopes
https://www.googleapis.com/auth/bigquery
ServiceAccountImpersonationTokenLifetime
3600
SSLTrustStore
SSLTrustStorePwd
SSLTrustStore
property.SWA_ActivationRowCount
executeBatch insert
rows which, when
exceeded, causes the connector to switch to the
Storage Write API.3
SWA_AppendRowCount
1000
Timeout
0
UniverseDomain
googleapis.com
UnsupportedHTAPIFallback
TRUE
) or returns an error (when set to FALSE
).TRUE
UseQueryCache
TRUE
Run queries with the driver
With your Java application connected to BigQuery through the JDBC driver, you can now run queries in your development environment through the standard JDBC process . All BigQuery quotas and limits apply.
Data type mapping
When you run queries through the JDBC driver for BigQuery, the following data type mapping occurs:
| GoogleSQL type | Java type |
|---|---|
ARRAY
|
Array
|
BIGNUMERIC
|
BigDecimal
|
BOOL
|
Boolean
|
BYTES
|
byte[]
|
DATE
|
Date
|
DATETIME
|
String
|
FLOAT64
|
Double
|
GEOGRAPHY
|
String
|
INT64
|
Long
|
INTERVAL
|
String
|
JSON
|
String
|
NUMERIC
|
BigDecimal
|
STRING
|
String
|
STRUCT
|
Struct
|
TIME
|
Time
|
TIMESTAMP
|
Timestamp
|
Examples
The following sections provide examples that use BigQuery features through the JDBC driver for BigQuery.
Positional parameters
The following example runs a query with a positional parameter :
PreparedStatement preparedStatement = connection . prepareStatement ( "SELECT * FROM MyTestTable where testColumn = ?" ); preparedStatement . setString ( 1 , "string2" ); ResultSet resultSet = statement . executeQuery ( selectQuery );
Nested and repeated records
The following example queries the base record of Struct
data:
ResultSet resultSet = statement . executeQuery ( "SELECT STRUCT(\"Adam\" as name, 5 as age)" ); resultSet . next (); Struct obj = ( Struct ) resultSet . getObject ( 1 ); System . out . println ( obj . toString ());
The driver returns the base record as a struct object or a string representation of a JSON object. The result is similar to the following:
{
"v": {
"f": [
{
"v": "Adam"
},
{
"v": "5"
}
]
}
}
The following example queries the subcomponents of a Struct
object:
ResultSet resultSet = statement . executeQuery ( "SELECT STRUCT(\"Adam\" as name, 5 as age)" ); resultSet . next (); Struct structObject = ( Struct ) resultSet . getObject ( 1 ); Object [] structComponents = structObject . getAttributes (); for ( Object component : structComponents ){ System . out . println ( component . toString ()); }
The following example queries a standard array of repeated data, then verifies the result:
// Execute Query ResultSet resultSet = statement . executeQuery ( "SELECT [1,2,3]" ); resultSet . next (); Object [] arrayObject = ( Object [] ) resultSet . getArray ( 1 ). getArray (); // Verify Result int count = 0 ; for (; count < arrayObject . length ; count ++ ) { System . out . println ( arrayObject [ count ] ); }
The following example queries a Struct
array of repeated data, then verifies
the result:
// Execute Query ResultSet resultSet = 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 Result for ( int count = 0 ; count < arrayObject . length ; count ++ ) { System . out . println ( arrayObject [ count ] ); }
Bulk-insert
The following example performs a bulk-insert operation with the executeBatch
method
.
Connection conn = DriverManager . getConnection ( connectionUrl ); PreparedStatement statement = null ; Statement st = conn . createStatement (); final String insertQuery = String . format ( "INSERT INTO `%s.%s.%s` " + " (StringField, IntegerField, BooleanField) VALUES(?, ?, ?);" , DEFAULT_CATALOG , DATASET , TABLE_NAME ); statement = conn . prepareStatement ( insertQuery1 ); for ( int i = 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 you don't need any additional licenses to use the drivers. However, when you use the driver, standard BigQuery pricing applies.
What's next
- Learn more about the Simba ODBC driver for BigQuery .
- Explore other BigQuery developer tools .

