SQL Server JDBC Java Example: Connect & Query Guide

Robert Jul 13, 2026

Connecting your Java applications with SQL Server has never been easier, thanks to the JDBC driver. JDBC, or Java Database Connectivity, allows Java applications to connect with databases like SQL Server, and provides a standardized way to access and manipulate data from a SQL database. In this guide, we'll walk you through a comprehensive example of how to connect to SQL Server using JDBC in Java.

Introduction to JDBC | Java Database Connectivity
Introduction to JDBC | Java Database Connectivity

Before we dive into the examples, make sure you have the SQL Server JDBC driver added to your project's classpath. You can find it in the Maven Central Repository as `mssql-jdbc`. If you're using Maven, add this to your pom.xml:

JDBC in Java
JDBC in Java

```xml com.microsoft.sqlserver mssql-jdbc 9.4.0.jre8 ```

Establishing the Connection

The first step is to establish a connection with the SQL Server database. To do this, we'll use the `java.sql.DriverManager` class.

JDBC ResultSet Example with the SQL Server Database
JDBC ResultSet Example with the SQL Server Database

The following code snippet demonstrates how to establish a connection to a SQL Server database:

```java String url = "jdbc:sqlserver://localhost:1433;databaseName=testDB;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;"; String user = "your_username"; String password = "your_password"; try (Connection connection = DriverManager.getConnection(url, user, password)) { // Your code here } catch (SQLException e) { // Handle exception } ```

Handling Connection Errors

JDBC in Java Explained | Database Connectivity Easy Notes
JDBC in Java Explained | Database Connectivity Easy Notes

When connecting to a database, it's important to handle any potential exceptions that may occur. The code above demonstrates a basic try-catch block for handling `SQLException`s.

Here's an example of how you might log or handle these errors more effectively:

```java try (Connection connection = DriverManager.getConnection(url, user, password)) { // Your code here } catch (SQLException e) { log.error("Failed to connect to the database", e); // Re-throwing the exception or exiting gracefully depends on your application's needs } ```

Closing the Connection

SQL Server Database Change Management with Liquibase
SQL Server Database Change Management with Liquibase

The connection to the database should be closed once it's no longer needed. In the example above, we're using a try-with-resources statement, which automatically closes the connection after the try block executes.

Executing Queries

Once you have a connection to the database, you can execute SQL queries using a `Statement`, `PreparedStatement`, or `CallableStatement` object.

Difference Between JDBC Statement and PreparedStatement
Difference Between JDBC Statement and PreparedStatement

Here's an example of how to execute a simple SELECT query and process the results:

```java String sql = "SELECT * FROM my_table"; try (Connection connection = DriverManager.getConnection(url, user, password); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql)) { while (resultSet.next()) { System.out.printf("%d: %s%n", resultSet.getInt("id"), resultSet.getString("name")); } } ```

Parameterized Queries

SQL Basics Tutorial for Beginners – Structured Query Language Commands, Syntax & Examples Guide
SQL Basics Tutorial for Beginners – Structured Query Language Commands, Syntax & Examples Guide
a poster with the names and symbols for different types of letters
a poster with the names and symbols for different types of letters
Sql Cheat Sheet, Learn Sql, Learn Web Development, Excel Tutorials, Sql Server, Career Options, Data Analyst, Data Scientist, Data Analysis
Sql Cheat Sheet, Learn Sql, Learn Web Development, Excel Tutorials, Sql Server, Career Options, Data Analyst, Data Scientist, Data Analysis
an image of the server list for windows and mac oss servers, with different types of
an image of the server list for windows and mac oss servers, with different types of
SQL Server JDBC Driver Download from Maven & Connection Example
SQL Server JDBC Driver Download from Maven & Connection Example
Free SQL Database Book
Free SQL Database Book
an image of a computer screen with code numbers on it and the words'datatables'in different languages
an image of a computer screen with code numbers on it and the words'datatables'in different languages
a diagram showing the different types of graphs and their corresponding data points for each point
a diagram showing the different types of graphs and their corresponding data points for each point
SQL Command Types
SQL Command Types
SQL & Databases Cheat Sheet for Developers
SQL & Databases Cheat Sheet for Developers
JVM Explained
JVM Explained
SQL CHARINDEX() Explained with Examples | Find Text Position in SQL Server
SQL CHARINDEX() Explained with Examples | Find Text Position in SQL Server
- The Knowledge Hub
- The Knowledge Hub
Java Cheatsheet
Java Cheatsheet
SQL ORDER BY Explained with Examples | Sort Data in SQL
SQL ORDER BY Explained with Examples | Sort Data in SQL
an image of a computer screen with some type of text on it, and another screenshot
an image of a computer screen with some type of text on it, and another screenshot
SQL Subquery
SQL Subquery
SQL CASE WHEN Explained with Examples | Beginner SQL Tutorial
SQL CASE WHEN Explained with Examples | Beginner SQL Tutorial
a screenshot of a web page with the text,'save all or nothing '
a screenshot of a web page with the text,'save all or nothing '
6 JDBC Performance Tips for Java Developers
6 JDBC Performance Tips for Java Developers

Using parameterized queries can help prevent SQL injection attacks and improve performance. Here's an example that demonstrates how to use a `PreparedStatement` with parameters:

```java String sql = "SELECT * FROM my_table WHERE id = ?"; int id = 1; try (Connection connection = DriverManager.getConnection(url, user, password); PreparedStatement preparedStatement = connection.prepareStatement(sql)) { preparedStatement.setInt(1, id); try (ResultSet resultSet = preparedStatement.executeQuery()) { if (resultSet.next()) { System.out.printf("%d: %s%n", resultSet.getInt("id"), resultSet.getString("name")); } } } ```

Stored Procedures

In some cases, you might want to use stored procedures for more complex tasks. You can execute a stored procedure using a `CallableStatement` like this:

```java String sql = "{call my_stored_procedure(?, ?)}"; int inputParameter = 1; int outputParameter = 0; try (Connection connection = DriverManager.getConnection(url, user, password); CallableStatement callableStatement = connection.prepareCall(sql)) { callableStatement.setInt(1, inputParameter); callableStatement.registerOutParameter(2, Types.INTEGER); callableStatement.execute(); int result = callableStatement.getInt(2); System.out.printf("Result: %d%n", result); } ```

Now that we've covered the basics of connecting to SQL Server using JDBC in Java, you should have a solid understanding of how to execute various types of queries and handle common exceptions. As with any learning process, practice makes perfect, so keep experimenting and expanding your knowledge of JDBC and SQL Server.

Don't forget to explore the official Microsoft documentation for more detailed information and advanced topics, such as connection pooling, batch updates, and working with specific data types.

Happy coding, and may your Java-SQL Server adventures be successful and enjoyable!