Configuring the JDBC Driver

This topic describes how to configure the JDBC driver, including how to connect to Snowflake using the driver.

Note

The connection parameters are now documented in the JDBC Driver Connection Parameter Reference.

In this Topic:

JDBC Driver Class

Use net.snowflake.client.jdbc.SnowflakeDriver as the driver class in your JDBC application.

Note

  • Don’t reference any other Snowflake classes or methods in your application code as they are subject to change in the future to implement improvements and fixes.

  • The previous driver class, com.snowflake.client.jdbc.SnowflakeDriver, is still supported but is deprecated (i.e. it will be removed in a future release, TBD). As such, any code that references the previous class name will continue to work, but you should update the code to reference the new class name now that the change has been implemented.

JDBC Driver Connection String

Using the JDBC driver to connect to Snowflake requires a connection string with the following syntax.

Syntax

jdbc:snowflake://<account_identifier>.snowflakecomputing.com/?<connection_params>

Connection Parameters

Note

For documentation on individual connection parameters, see the JDBC Driver Connection Parameter Reference.

<account_identifier>

Specifies the account identifier for your Snowflake account. For details, see Account Identifiers. For examples of the account identifier used in a JDBC connection string, see Examples.

<connection_params>

Specifies a series of one or more parameters, in the form of <param>=<value>, with each parameter separated by the ampersand character (&), and no spaces anywhere in the connection string.

If you need to set parameter values that use spaces, ampersands (&), equals signs (=), or other special characters, you should URL-encode the special characters. For example, if you need to specify a value that contains a space, ampersand, and equals sign:

String connectionURL = "jdbc:snowflake://myorganization-myaccount.snowflakecomputing.com/?query_tag='folder=folder1 folder2&'

encode the space as %20, the ampersand as %26, and the equals sign as %3D:

String connectionURL = "jdbc:snowflake://myorganization-myaccount.snowflakecomputing.com/?query_tag='folder%3Dfolder1%20folder2%26'

As an alternative, rather than specifying these parameters in the connection string, you can set these parameters in a Properties object that you pass to the DriverManager.getConnectionIO method.

Properties props = new Properties();
props.put("parameter1", parameter1Value);
props.put("parameter2", parameter2Value);
Connection con = DriverManager.getConnection("jdbc:snowflake://<account_identifier>.snowflakecomputing.com/", props);

Note

For documentation on individual connection parameters, see the JDBC Driver Connection Parameter Reference.

Other Parameters

Any session parameter can be included in the connection string. For example:

CLIENT_SESSION_KEEP_ALIVE=<Boolean>

Specifies whether to keep the current session active after a period of inactivity, or to force the user to login again. If the value is true, Snowflake keeps the session active indefinitely, even if there is no activity from the user. If the value is false, the user must log in again after four hours of inactivity.

Default is false.

For descriptions of all the session parameters, see Parameters.

Examples

The following is an example of the connection string that uses an account identifier that specifies the account myaccount in the organization myorganization.

jdbc:snowflake://myorganization-myaccount.snowflakecomputing.com/?user=peter&warehouse=mywh&db=mydb&schema=public

The following is an example of a connection string that uses the account locator xy12345 as the account identifier:

jdbc:snowflake://xy12345.snowflakecomputing.com/?user=peter&warehouse=mywh&db=mydb&schema=public

Note that this example uses an account in the AWS US West (Oregon) region. If the account is in a different region or if the account uses a different cloud provider, you need to specify additional segments after the account locator.

Using Single Sign-on (SSO) For Authentication

If you have configured Snowflake to use single sign-on (SSO), you can configure your client application to use SSO for authentication. See Using SSO with Client Applications That Connect to Snowflake for details.

Using Multi-Factor Authentication

Snowflake supports caching MFA tokens, including combining MFA token caching with SSO.

For more information, see Using MFA Token Caching to Minimize the Number of Prompts During Authentication — Optional.

Using Key Pair Authentication & Key Rotation

The Snowflake JDBC driver supports key pair authentication and key rotation. This authentication method requires a 2048-bit (minimum) RSA key pair.

To start, complete the initial configuration for key pair authentication as shown in Key Pair Authentication & Key Pair Rotation.

Next, choose one of the following three options to configure either the JDBC connection properties or the JDBC connection string.

  1. Specify the private key via the privateKey property in the connection properties.

  2. Specify the private key file name and password for that file as separate properties in the connection properties.

  3. Specify the private key file name and password for that file as part of the connection string.

These options are described in more detail in the next three sections.

privateKey Property in Connection Properties

This section provides an example of setting the privateKey property to a private key in a file.

This example uses the Bouncy Castle Crypto APIs. In order to compile and run this example, you must include the following JAR files in your classpath:

  • the provider JAR file (bcprov-jdkversions.jar)

  • the PKIX / CMS / EAC / PKCS / OCSP / TSP / OPENSSL JAR file (bcpkix-jdkversions.jar)

where versions specifies the versions of the JDK that the JAR file supports.

To use this example:

  1. Copy the sample code below, and replace the following placeholder values:

    Placeholder

    Description

    path/rsa_key.p8

    Set this to the path and name of the private key file that you generated earlier.

    private_key_passphrase

    If you generated an encrypted key, implement the getPrivateKeyPassphrase() method to return the passphrase for decrypting that key.

    account_identifier

    Set this to your account identifier.

    user

    Set this to your Snowflake login name.

    database_name

    Set this to the name of the database that you want to use.

    schema_name

    Set this to the name of schema that you want to use.

    warehouse_name

    Set this to the name of warehouse that you want to use.

    role

    Set this to the name of role that you want to use.

  2. Compile and run the sample code. Include the Bouncy Castle JAR files in the classpath.

    For example, on Linux and macOS:

    javac -cp bcprov-jdk<versions>.jar:bcpkix-jdk<versions>.jar TestJdbc.java
    
    java -cp .:snowflake-jdbc-<ver>.jar:bcprov-jdk<versions>.jar:bcpkix-jdk<versions>.jar TestJdbc.java
    

    On Windows:

    javac -cp bcprov-jdk<versions>.jar;bcpkix-jdk<versions>.jar TestJdbc.java
    
    java -cp .;snowflake-jdbc-<ver>.jar;bcprov-jdk<versions>.jar;bcpkix-jdk<versions>.jar TestJdbc.java
    

Sample code

import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder;
import org.bouncycastle.operator.InputDecryptorProvider;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo;
import org.bouncycastle.pkcs.PKCSException;

import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Paths;
import java.security.PrivateKey;
import java.security.Security;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.DriverManager;
import java.util.Properties;

public class TestJdbc
{
  // Path to the private key file that you generated earlier.
  private static final String PRIVATE_KEY_FILE = "/<path>/rsa_key.p8";

  public static class PrivateKeyReader
  {

    // If you generated an encrypted private key, implement this method to return
    // the passphrase for decrypting your private key.
    private static String getPrivateKeyPassphrase() {
      return "<private_key_passphrase>";
    }

    public static PrivateKey get(String filename)
            throws Exception
    {
      PrivateKeyInfo privateKeyInfo = null;
      Security.addProvider(new BouncyCastleProvider());
      // Read an object from the private key file.
      PEMParser pemParser = new PEMParser(new FileReader(Paths.get(filename).toFile()));
      Object pemObject = pemParser.readObject();
      if (pemObject instanceof PKCS8EncryptedPrivateKeyInfo) {
        // Handle the case where the private key is encrypted.
        PKCS8EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) pemObject;
        String passphrase = getPrivateKeyPassphrase();
        InputDecryptorProvider pkcs8Prov = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(passphrase.toCharArray());
        privateKeyInfo = encryptedPrivateKeyInfo.decryptPrivateKeyInfo(pkcs8Prov);
      } else if (pemObject instanceof PrivateKeyInfo) {
        // Handle the case where the private key is unencrypted.
        privateKeyInfo = (PrivateKeyInfo) pemObject;
      }
      pemParser.close();
      JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME);
      return converter.getPrivateKey(privateKeyInfo);
    }
  }

  public static void main(String[] args)
      throws Exception
  {
    String url = "jdbc:snowflake://<account_identifier>.snowflakecomputing.com";
    Properties prop = new Properties();
    prop.put("user", "<user>");
    prop.put("privateKey", PrivateKeyReader.get(PRIVATE_KEY_FILE));
    prop.put("db", "<database_name>");
    prop.put("schema", "<schema_name>");
    prop.put("warehouse", "<warehouse_name>");
    prop.put("role", "<role_name>");

    Connection conn = DriverManager.getConnection(url, prop);
    Statement stat = conn.createStatement();
    ResultSet res = stat.executeQuery("select 1");
    res.next();
    System.out.println(res.getString(1));
    conn.close();
  }
}

Note

Use forward slashes as file path separators on all operating systems, including Windows. The JDBC driver replaces forward slashes with the appropriate path separator for the platform.

Private Key File Name and Password as Connection Properties

You can specify the private key file name and password as separate connection properties, for example:

Properties props = new Properties();
props.put("private_key_file", "/tmp/rsa_key.p8");
props.put("private_key_file_pwd", "dummyPassword");
Connection connection = DriverManager.getConnection("jdbc:snowflake://myorganization-myaccount.snowflake.com", props);

If you specify the private_key_file and private_key_file_pwd parameters, do not specify the privateKey parameter in the connection properties.

Note

Use forward slashes as file path separators on all operating systems, including Windows. The JDBC driver replaces forward slashes with the appropriate path separator for the platform.

Private Key File Name and Password in Connection String

You can specify the private key file name and password in the connection string, as shown below:

Connection connection = DriverManager.getConnection(
    "jdbc:snowflake://myorganization-myaccount.snowflake.com/?private_key_file=/tmp/rsa_key.p8&private_key_file_pwd=dummyPassword",
    props);

Note

Use forward slashes as file path separators on all operating systems, including Windows. The JDBC driver replaces forward slashes with the appropriate path separator for the platform.

If you specify the private key and password in the connection string, then do not specify the parameters private_key_file, private_key_file_pwd, or privateKey in the connection properties.

Verifying the Network Connection to Snowflake with SnowCD

After configuring your driver, you can evaluate and troubleshoot your network connectivity to Snowflake using SnowCD.

You can use SnowCD during the initial configuration process and on-demand at any time to evaluate and troubleshoot your network connection to Snowflake.

Connecting Using a Proxy Server

There are two ways to use a proxy server with the Snowflake JDBC Driver:

  • Set system properties for your proxy settings in the JVM (Java Virtual Machine) for your client application.

  • Include the proxy host and port information in the JDBC connection string or the Properties object passed to the DriverManager.getConnection() method.

Both techniques are documented below.

Note

Proxy settings in the connection string override the proxy system properties that are set in the JVM.

Tip

Snowflake’s security model does not allow Secure Sockets Layer (SSL) proxies (using an HTTPS certificate). Your proxy server must use a publicly-available Certificate Authority (CA), reducing potential security risks such as a MITM (Man In The Middle) attack through a compromised proxy.

If you must use your SSL proxy, we strongly recommend that you update the server policy to pass through the Snowflake certificate such that no certificate is altered in the middle of communications.

As an alternative, you can set the nonProxyHosts parameter in the connection string or Properties object to bypass the proxy for specific communications. For example, Amazon S3 access can be bypassed by specifying nonProxyHosts=".amazonaws.com".

Specifying a Proxy Server by Setting Java System Properties

To connect through a proxy server, you can set the proxy system properties. You can either set these in your code or pass them on the command line to the JVM (Java virtual machine) for your client application.

To set the system properties in your code, call System.setProperty:

System.setProperty("http.useProxy", "true");
System.setProperty("http.proxyHost", "proxyHost Value");
System.setProperty("http.proxyPort", "proxyPort Value");
System.setProperty("https.proxyHost", "proxyHost HTTPS Value");
System.setProperty("https.proxyPort", ""proxyPort HTTPS Value"")

To pass the system properties on the command line to your JVM, use the -D command-line option:

-Dhttp.useProxy=true
-Dhttps.proxyHost=<proxy_host>
-Dhttp.proxyHost=<proxy_host>
-Dhttps.proxyPort=<proxy_port>
-Dhttp.proxyPort=<proxy_port>

To bypass the proxy for one or more IP addresses or hosts, set the http.nonProxyHosts system property to the list of these hosts:

  • Use a pipe symbol (|) to separate the host names.

  • To specify hostnames that match a pattern, use an asterisk (*) as a wildcard character.

The following example demonstrates how to set this system property on the command line:

-Dhttp.nonProxyHosts="*.my_company.com|localhost|myorganization-myaccount.snowflakecomputing.com|192.168.91.*"

Specifying a Proxy Server in the JDBC Connection String

Note

Specifying the proxy information as part of the URL is less secure than other methods of specifying the proxy information.

To use a proxy server by setting the following parameters in the JDBC connection string:

If your proxy server does not require authentication, you can omit the proxyUser and proxyPassword parameters.

If your proxy server connection requires authentication using a proxy username and proxy password, those credentials may be exposed as plain text by other applications when using the HTTP protocol. To avoid exposing these credentials, use the proxyProtocol parameter to specify the HTTPS protocol.

jdbc:snowflake://<account_identifier>.snowflakecomputing.com/?warehouse=<warehouse_name>&useProxy=true&proxyHost=<ip_address>&proxyPort=<port>&proxyUser=test&proxyPassword=test

For example:

jdbc:snowflake://myorganization-myaccount.snowflakecomputing.com/?warehouse=DemoWarehouse1&useProxy=true&proxyHost=172.31.89.76&proxyPort=8888&proxyUser=test&proxyPassword=test

The proxy settings specified in the connection string override the proxy system properties in the JVM.

Bypassing the Proxy Server

If you need to bypass the proxy server when connecting to one or more hosts, specify the list of hosts in the nonProxyHosts parameter:

&nonProxyHosts=<bypass_proxy_for_these_hosts>

Separate the hostnames with a URL-escaped pipe symbol (%7C). You can also use an asterisk (*) as a wildcard. For example:

&nonProxyHosts=*.my_company.com%7Clocalhost%7Cmyorganization-myaccount.snowflakecomputing.com%7C192.168.91.*

Specifiyng the Protocol Used to Connect to the Proxy Server

You can use the proxyProtocol parameter to specify the protocol used to connect to the proxy server. The default value is http. Valid values are http and https.

For example:

&proxyProtocol=https

OCSP

When the driver connects, Snowflake sends a certificate to confirm that the connection is to Snowflake rather than to a host that is impersonating Snowflake. The driver sends that certificate to an OCSP (Online Certificate Status Protocol) server to verify that the certificate has not been revoked.

If the driver cannot reach the OCSP server to verify the certificate, the driver can “fail open” or “fail closed”.

Choosing Fail-Open or Fail-Close Mode

JDBC Driver versions prior to 3.8.0 default to fail-close. Versions 3.8.0 and later default to fail-open. You can override the default behavior in any of the following ways:

  • Set the connection property ocspFailOpen to true or false. For example:

    Properties connection_properties = new Properties();
    connection_properties.put("ocspFailOpen", "false");
    ...
    connection = DriverManager.getConnection(connectionString, connection_properties);
    
  • Set the system property net.snowflake.jdbc.ocspFailOpen to true or false. For example:

    Properties p = new Properties(System.getProperties());
    p.put("net.snowflake.jdbc.ocspFailOpen", "false");
    System.setProperties(p);
    

Verifying the OCSP Connector or Driver Version

For more information about the driver or connector version, configuration, and OCSP behavior, see OCSP Configuration.

OCSP Response Cache Server

Note

The OCSP response cache server is currently supported by the Snowflake JDBC Driver 3.6.0 and higher.

Snowflake clients initiate every connection to a Snowflake service endpoint with a “handshake” that establishes a secure connection before actually transferring data. As part of the handshake, a client authenticates the TLS/SSL certificate for the service endpoint. The revocation status of the certificate is checked by sending a client certificate request to one of the OCSP (Online Certificate Status Protocol) servers for the CA (certificate authority).

A connection failure occurs when the response from the OCSP server is delayed beyond a reasonable time. The following caches persist the revocation status, helping alleviate these issues:

  • Memory cache, which persists for the life of the process.

  • File cache, which persists until the cache directory (e.g. ~/.cache/snowflake or ~/.snowsql/ocsp_response_cache) is purged.

  • Snowflake OCSP response cache server, which fetches OCSP responses from the CA’s OCSP servers hourly and stores them for 24 hours. Clients can then request the validation status of a given Snowflake certificate from this server cache.

    Important

    If your server policy denies access to most or all external IP addresses and web sites, you must whitelist the cache server address to allow normal service operation. The cache server hostname is ocsp*.snowflakecomputing.com:80.

    If you need to disable the cache server for any reason, set the SF_OCSP_RESPONSE_CACHE_SERVER_ENABLED environment variable to false. Note that the value is case-sensitive and must be in lowercase.

If none of the cache layers contain the OCSP response, the client then attempts to fetch the validation status directly from the OCSP server for the CA.

File Caches

To improve usability, the driver uses file caches for authentication and OCSP responses. By default, these files are stored in the following directories:

Linux

~/.cache/snowflake

macOS

~/Library/Caches/Snowflake

Windows

%USERPROFILE%AppDataLocalSnowflakeCaches

If the JDBC application user does not have a user profile in the local operating system, the driver attempts to store the cache files in the temporary directory. You can configure the driver to write cache files to another directory using the following environment variables:

SF_TEMPORARY_CREDENTIAL_CACHE_DIR=string

Specifies the location of the temporary credential cache file in a local directory. This can also be configured with the JVM option -Dnet.snowflake.jdbc.temporaryCredentialCacheDir=string on launch.

SF_OCSP_RESPONSE_CACHE_DIR=string

Specifies the location of the OCSP response cache file in a local directory. This can also be configured with the JVM option -Dnet.snowflake.jdbc.ocspResponseCacheDir=string on launch.

For more information, see OCSP Response Cache Server (in this topic).

Note that the JVM options should be set on launch, and not programmatically (via System.setProperty()). If both environment variable and JVM options are provided, the JVM option will be used.

Configuring JDBC Logging

Starting with version 3.0.4, the JDBC driver supports two logging frameworks:

  • Java Core Logging Facilities

  • Simple Logging Facade for Java

Java Core Logging Facilities (java.util.logging)

To use this logger, specify the following option for the JVM:

-Dnet.snowflake.jdbc.loggerImpl=net.snowflake.client.log.JDK14Logger

Then, you can customize the logging configuration using the application programming interface (API) for the logger. For more details, see the java.util.logging Package documentation.

For example, create a file named logging.properties that includes the following contents:

###########################################################
#   Default Logging Configuration File
#
# You can use a different file by specifying a filename
# with the java.util.logging.config.file system property.
# For example java -Djava.util.logging.config.file=myfile
############################################################

############################################################
#   Global properties
############################################################

# "handlers" specifies a comma-separated list of log Handler
# classes.  These handlers will be installed during VM startup.
# Note that these classes must be on the system classpath.
# ConsoleHandler and FileHandler are configured here such that
# the logs are dumped into both a standard error and a file.
handlers = java.util.logging.ConsoleHandler, java.util.logging.FileHandler

# Default global logging level.
# This specifies which kinds of events are logged across
# all loggers.  For any given facility this global level
# can be overriden by a facility specific level.
# Note that the ConsoleHandler also has a separate level
# setting to limit messages printed to the console.
.level = INFO

############################################################
# Handler specific properties.
# Describes specific configuration information for Handlers.
############################################################

# default file output is in the tmp dir
java.util.logging.FileHandler.pattern = /tmp/snowflake_jdbc%u.log
java.util.logging.FileHandler.limit = 5000000000000000
java.util.logging.FileHandler.count = 10
java.util.logging.FileHandler.level = INFO
java.util.logging.FileHandler.formatter = net.snowflake.client.log.SFFormatter

# Limit the messages that are printed on the console to INFO and above.
java.util.logging.ConsoleHandler.level = INFO
java.util.logging.ConsoleHandler.formatter = net.snowflake.client.log.SFFormatter

# Example to customize the SimpleFormatter output format
# to print one-line log message like this:
#     <level>: <log message> [<date/time>]
#
# java.util.logging.SimpleFormatter.format=%4$s: %5$s [%1$tc]%n

############################################################
# Facility specific properties.
# Provides extra control for each logger.
############################################################

# Snowflake JDBC logging level.
net.snowflake.level = INFO
net.snowflake.handler = java.util.logging.FileHandler

Specify the JVM parameters in the command line:

java -jar application.jar -Dnet.snowflake.jdbc.loggerImpl=net.snowflake.client.log.JDK14Logger -Djava.util.logging.config.file=logging.properties

Where application.jar references the application code for the JDBC driver. The log files are located in /tmp/snowflake_jdbc*.

Simple Logging Facade for Java (org.slf4j)

If a logger implementation package (i.e. org.sl4j:sl4j-jdk14 or org.sl4j:slf4j-log4j12) or a custom logger (i.e. your own org.slf4j.impl.StaticLoggerBinder class) has been defined on the classpath, then the driver automatically uses this logger.

You can also explicitly choose to use this logger by specifying the following JVM option:

-Dnet.snowflake.jdbc.loggerImpl=net.snowflake.client.log.SLF4JLogger.

For more information, see the Simple Logging Facade for Java (SLF4J) documentation.

Note

If you do not explicitly specify a logger for the driver using either of the JVM options described above and you do not have a custom logger defined on the classpath (or you are using a driver version earlier than 3.0.4), the driver uses java.util.logging by default. However, the following default behavior applies:

  • You cannot specify where the log file is written. It is always written to the directory specified by the java.io.tmpDir system property:

    • In Linux and macOS environments, the default directory is usually either /tmp or /var/tmp.

    • In Windows environments, the default directory is usually C:\temp.

  • The logging level is determined by the tracing connection parameter (see above).

Troubleshooting Tips

Ensure Properties Are Set Correctly

The DriverManager.getConnection() method reads only the values of the Properties parameter that match specific, predefined names (“password”, “warehouse”, etc.). If you misspell a property name, or include extra properties, the driver ignores those properties without issuing an error or warning message. This can make it difficult to detect minor misspellings.

Use the Right Values for Connection String and Account

If you can’t establish a connection, verify that you are specifying the account identifier correctly in the JDBC connection string. For more information about account identifiers, see account identifier.