ערוך

Microsoft JDBC Driver for SQL Server

Download JDBC driver

The Microsoft Java Database Connectivity (JDBC) Driver for SQL Server is a Type 4 JDBC driver (pure Java, talks the SQL Server TDS protocol directly, no native libraries required) that lets any Java application or application server connect to SQL Server, Azure SQL Database, Azure SQL Managed Instance, and SQL database in Microsoft Fabric. It implements the standard JDBC APIs and works with major Java application servers, including IBM WebSphere and SAP NetWeaver.

Choose your starting point

Production baseline for Azure SQL

Use this snippet as a starting point for a production-oriented Azure SQL connection. It loads the server name and database name from application configuration, such as Azure App Service app settings, environment variables, or a config file, and sets the rest of the connection properties programmatically. The configuration combines Transport Layer Security (TLS), managed identity, login retries on transient failures, fast failover-group recovery, a longer login timeout to cover a first-touch failover, and configurable retry logic (CRL) for statements that hit Azure SQL throttling or mid-query failover.

For higher security and easier scale-out, keep connection information outside your code. In production, store connection information in your application's configuration system, and use Azure Key Vault for sensitive values and centrally managed connection settings. For more information, see Securing connection strings.

The Java snippets in this article omit imports and class wrappers for brevity.

// Load endpoint details from application configuration. In Azure App Service,
// these can come from app settings or Key Vault-backed settings.
String serverName = System.getenv("SQL_SERVER_NAME");
String databaseName = System.getenv("SQL_DATABASE_NAME");
String port = System.getenv().getOrDefault("SQL_PORT", "1433");

if (serverName == null || databaseName == null) {
    throw new IllegalStateException(
            "Set SQL_SERVER_NAME and SQL_DATABASE_NAME in your application configuration.");
}

String url = "jdbc:sqlserver://" + serverName + ":" + port;

Properties props = new Properties();
props.setProperty("databaseName", databaseName);
props.setProperty("encrypt", "true");
props.setProperty("trustServerCertificate", "false");
props.setProperty("authentication", "ActiveDirectoryManagedIdentity");
props.setProperty("loginTimeout", "120");         // 90 is the minimum floor for this retry profile; 120 leaves practical failover margin
props.setProperty("connectRetryCount", "5");     // retry transient login failures up to 5 times (default 1)
props.setProperty("connectRetryInterval", "15"); // 15 seconds between login retries (default 10)
props.setProperty("multiSubnetFailover", "true"); // recommended for any Azure SQL HA listener
// props.setProperty("applicationIntent", "ReadOnly"); // uncomment to route to a readable secondary
// Retry deadlocks and lock timeouts, plus Azure SQL throttling and mid-query failover.
props.setProperty("retryExec", "1205,1222:3,5+5;40501,40613,40197,10928,10929,49918:4,5*2");

try (Connection conn = DriverManager.getConnection(url, props);
     Statement stmt = conn.createStatement();
     ResultSet rs = stmt.executeQuery("SELECT 1")) {
    while (rs.next()) {
        System.out.println(rs.getInt(1));
    }
}

This snippet is tuned for Azure SQL Database failover groups and Azure SQL Managed Instance.

Set multiSubnetFailover=true only when you connect to a failover-group listener, availability group listener, or failover cluster instance endpoint. Using this property against endpoints that aren't high availability (HA) listeners can hurt performance and isn't supported. For more information, see JDBC driver support for High Availability, disaster recovery.

The snippet doesn't set retryConn because the driver already retries the most common Azure SQL transient login errors (including 4060, 40197, 40501, 40613, 49918, 49919, 49920, 10928, and 10929) out of the box, gated by connectRetryCount and connectRetryInterval. For the full list, see Built-in transient login error list. Add retryConn with +<errorNumber> only when you need to extend the list with an error that isn't already covered, or set it to <errorNumber> (no leading +) to replace it. If you place the same value in a JDBC URL, wrap it as retryConn={+<errorNumber>} or retryConn={<errorNumber>}.

The retryExec property has two parts, written as rule1;rule2 when you set it programmatically. If you place the same value in a JDBC URL, wrap each rule in braces as {rule1};{rule2}:

  • {1205,1222:3,5+5} retries deadlock victims (1205) and lock-request timeouts (1222) three times with a linear backoff of 5, 10, and 15 seconds. For 1205, SQL Server rolls back the transaction before the driver sees the error, so rerunning a single statement is safe. If the deadlocked statement was part of a multistatement transaction, earlier statements were rolled back too and CRL doesn't replay them, so wrap the whole transaction in your own retry loop. 1222 leaves the transaction open and the statement-level retry only reruns the statement inside the original transaction; if you also need to bound transaction duration, wrap the whole transaction in your own retry loop.

  • {40501,40613,40197,10928,10929,49918:4,5*2} retries Azure SQL throttling, mid-query failover, and resource-limit errors four times with an exponential backoff of 5, 10, 20, and 40 seconds. These errors are in the built-in transient list for the connect loop, but retryExec is what catches them when they fire mid-query against an established connection. CRL backoffs are bounded by queryTimeout. If you set queryTimeout lower than the next planned wait, the driver gives up early and rethrows. Choose a queryTimeout that's at least as large as the total of your CRL waits plus statement runtime, or accept that the longest backoffs won't fire.

For Azure SQL Database failover groups, Hyperscale named replicas and read scale-out, or Always On availability group listeners, set applicationIntent=ReadOnly when you want to land on a readable secondary. For sovereign clouds where the certificate Subject Alternative Name (SAN) doesn't include the host you're connecting to, also set hostNameInCertificate to match (for example, *.database.usgovcloudapi.net for Azure Government).

For more information about each part of this configuration, see:

For the catalog of Azure SQL transient errors, see Troubleshoot transient connection errors.

Key features

  • Standards-based JDBC: Type 4 driver that's JDBC 4.2 compliant, with partial JDBC 4.3 support.
  • Wide platform support: Runs on any platform with a supported Java Virtual Machine (JVM), including Windows, Linux, and macOS.
  • Encrypted by default: TLS-encrypted connections with encrypt=true as the default for current drivers.
  • Microsoft Entra ID authentication: Passwordless connections with managed identity, service principal, interactive, integrated, default credential chain, and access-token flows.
  • Kerberos and NTLM: Integrated authentication for on-premises Active Directory deployments.
  • Always Encrypted: Client-side encryption for sensitive columns, with optional secure enclaves for in-place operations.
  • Bulk copy: High-throughput inserts with the SQLServerBulkCopy API and batch-insert performance for executeBatch.
  • Connection resiliency: Built-in login retries for transient errors, plus opt-in configurable retry logic for statements and custom error numbers.
  • Rich SQL Server data type support: datetimeoffset, sql_variant, JSON, spatial, vector, table-valued parameters, and user-defined types.

Get started

Article Description
System requirements Supported Java, operating system, and SQL Server versions.
Support matrix Detailed compatibility matrix for JDBC driver releases.
Download Microsoft JDBC Driver for SQL Server Download links, Maven coordinates, and release artifacts.
Getting started with the JDBC driver Install the driver, configure your environment, and run your first query.
Overview of the JDBC driver Architecture, supported features, and JDBC specification compliance.

Configure and connect

Article Description
Connecting to SQL Server with the JDBC driver Open a connection to a SQL Server instance from Java.
Connect to an Azure SQL database Connect a Java application to Azure SQL Database.
Building the connection URL Full reference for jdbc:sqlserver:// URL syntax and properties.
Set the connection properties All connection properties, defaults, and how to set them.
Setting the data source properties Configure SQLServerDataSource for use with JNDI and app servers.
Working with a connection Open, reuse, and close connections correctly.
Using connection pooling JNDI data sources and integration with external pools.
Connection resiliency Built-in login retries and broken-connection detection.
Configurable retry logic Retry failed statements and customize the login retry list with retryExec and retryConn.
Understanding timeout properties in the JDBC driver loginTimeout, queryTimeout, socket timeouts, and how they interact.
Deploying the JDBC driver Package and deploy the driver with your application.

Authenticate

Article Description
Microsoft Entra authentication Managed identity, service principal, interactive, integrated, and access-token authentication.
Kerberos integrated authentication Connect with Kerberos and Active Directory.
NTLM authentication Use NTLM credentials to authenticate.
Client certificate authentication for loopback scenarios Authenticate clients with certificates on loopback connections.

Secure

Article Description
Securing JDBC driver applications Security guidance for Java applications that use the driver.
Application security Threat model and defense-in-depth recommendations.
Securing connection strings Keep credentials and connection strings out of source.
Configuring the client for encryption Trust roots, certificate pinning, and TLS settings.
Connecting with encryption Force encrypt=true and validate the server certificate.
Understanding encryption support How the driver negotiates TLS with SQL Server.
Validating user input Parameterize SQL and avoid injection.
FIPS mode Run the driver in FIPS-compliant environments.
Always Encrypted Configure client-side encryption for sensitive columns.
Always Encrypted with secure enclaves Enable rich operations on encrypted columns.
Always Encrypted API reference API surface for column encryption providers and key stores.

Work with data

Article Description
Working with statements and result sets Basics of Statement, PreparedStatement, and result sets.
Using statements with the JDBC driver Run parameterized and non-parameterized statements.
Handling complex statements Stored procedures, multiple results, and update counts.
Working with result sets Iterate, update, and scroll through query results.
Using multiple result sets Handle queries that return more than one result set.
Understanding cursor types Forward-only, scrollable, and updatable cursors.
Using table-valued parameters Pass TABLE parameters to stored procedures.
Using bulk copy with the JDBC driver High-throughput inserts with SQLServerBulkCopy.
Bulk copy API for batch insert Accelerate executeBatch for INSERT workloads.
Performing batch operations Batch inserts, updates, and deletes.

Data types

Article Description
Working with data types Map Java types to SQL Server types.
Understanding the JDBC driver data types Driver type system and JDBC mappings.
Data type conversions Implicit and explicit conversions between Java and SQL Server.
Data type differences Edge cases when mapping types across the boundary.
JSON data type Store and query JSON columns.
Spatial data types Use geometry and geography from Java.
Vector data type Work with the SQL Server vector type.
sql_variant Read and write sql_variant columns.
User defined types Use CLR user-defined types from Java.
National character set support Unicode handling and nvarchar columns.
International features Locale, collation, and globalization considerations.

Transactions and concurrency

Article Description
Performing transactions commit, rollback, and auto-commit semantics.
Understanding transactions Transaction lifecycle and best practices.
Isolation levels Snapshot, read committed, serializable, and others.
Concurrency control Optimistic and pessimistic concurrency strategies.
Row locking How SQL Server takes and releases row locks.
Using savepoints Partial rollback within a transaction.
Managing transaction size Tune transaction scope to avoid long-running locks.
XA transactions Two-phase commit with SQLServerXADataSource.

Performance and reliability

Article Description
Improving performance and reliability Index, query, and driver-level tuning.
Prepared statement metadata caching Reuse prepared statement plans.
Prepared statement parameter performance Parameter typing and execution plan reuse.
Adaptive buffering Stream large columns without loading them entirely into memory.
Closing objects when not in use Free Statement, ResultSet, and Connection resources promptly.
High availability and disaster recovery Availability group listeners and multi-subnet failover.
Database mirroring Use the driver with database mirroring partners.

Diagnose and troubleshoot

Article Description
Diagnosing problems with the JDBC driver Tracing, logging, and common failure modes.
Troubleshooting connectivity Connection errors, TLS handshake failures, and named instances.
Tracing driver operation Enable JDK logging for the driver.
Performance logger and callback Capture per-statement performance metrics.
Extended events log Correlate client errors with server-side extended events.
Handling errors SQLException, error codes, and retry hints.
Article Description
Release notes Version history and what's new in each release.
Feature dependencies Optional dependencies for Entra ID, Kerberos, Always Encrypted, and others.
JDBC 4.3 compliance JDBC 4.3 API conformance.
JDBC 4.2 compliance JDBC 4.2 API conformance.
JDBC 4.1 compliance JDBC 4.1 API conformance.
Compliance and legal Specification compliance and licensing.
Sample JDBC driver applications End-to-end code samples.
FAQ Frequently asked questions.