Connecting Java to SQL Server with JDBC: A Practical Guide

Java applications can communicate with Microsoft SQL Server through the Microsoft JDBC Driver. A connection string identifies the server, database, authentication method, and encryption settings.

Before you start

Install the supported Microsoft JDBC Driver and make it available on the application’s classpath or build dependency. Confirm the database engine is listening on the expected endpoint and the login has only the permissions it needs.

Example: a parameterized query

Create the connection and SQL statement inside try-with-resources blocks so JDBC closes them even when an exception occurs.

Example code

import java.sql.*;
public class SqlServerDemo {
  public static void main(String[] args) throws SQLException {
    String url = "jdbc:sqlserver://localhost:1433;"
               + "databaseName=TrainingDB;encrypt=true;"
               + "trustServerCertificate=false;";
    String sql = "SELECT ProductID, ProductName "
               + "FROM dbo.Products WHERE CategoryID = ?";
    try (Connection c = DriverManager.getConnection(
             url, System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));
         PreparedStatement p = c.prepareStatement(sql)) {
      p.setInt(1, 3);
      try (ResultSet rs = p.executeQuery()) {
        while (rs.next())
          System.out.println(rs.getInt(1) + ": " + rs.getString(2));
      }
    }
  }
}

Troubleshooting and safety

The sample assumes TrainingDB and the sample table exist. A production server must use a certificate trusted by the client; do not silently turn off encryption validation. Avoid hard-coded passwords, catch SQL exceptions at an application boundary, and use prepared statements for user-supplied values.


About this article: This AI-generated educational rewrite was prepared from an existing Open Education article, with new explanations and illustrative examples where helpful. Read the earlier article (post 76673). The new text may be freely copied, edited, and reused with or without attribution to this site. Third-party material, brand names, and linked resources retain their own rights. AI can make mistakes: verify syntax, version support, security practices, and outcomes against official documentation before use, especially in production.

Leave a Reply