September 23, 2024 By Matthew Rathbone

What is a JDBC Connection String?

A JDBC connection string is a URL that specifies the database host, port, and other parameters required to connect to a SQL Server database. This string provides all the necessary information for the JDBC driver to establish a connection.

Basic Structure of a JDBC SQL Server Connection String

The general format of a JDBC SQL Server connection string looks like this:

jdbc:sqlserver://[serverName[\instanceName][:portNumber]];[property=value[;property=value]]
  • jdbc:sqlserver:// - The protocol used for a JDBC connection.
  • serverName - The name or IP address of the server hosting the SQL Server instance.
  • instanceName (optional) - The specific SQL Server instance.
  • portNumber (optional) - The port to connect to. Defaults to 1433.
  • property=value - Additional properties to configure the connection (like database name, authentication details, etc.).

Example: Minimal JDBC Connection String

String connectionUrl = "jdbc:sqlserver://localhost:1433;";

This is the simplest form of a connection string where:

  • The database server is hosted locally.
  • The port is the default SQL Server port 1433.

Example: Full JDBC Connection String

For a more detailed setup, consider a scenario where you want to connect to a named instance on a remote server with specific credentials and database:

String connectionUrl = "jdbc:sqlserver://192.168.1.100\\SQLExpress:1433;"
                     + "databaseName=MyDatabase;"
                     + "user=myUsername;"
                     + "password=myPassword;";

Here’s what each part means:

  • 192.168.1.100\\SQLExpress:1433 - Connect to the instance SQLExpress on the server 192.168.1.100 using port 1433.
  • databaseName=MyDatabase - Connect to the specific database named MyDatabase.
  • user=myUsername and password=myPassword - These are the credentials used to authenticate.

Example with Integrated Windows Authentication

If your SQL Server is set up to use Windows Authentication, you can use the integratedSecurity parameter:

String connectionUrl = "jdbc:sqlserver://localhost:1433;"
                     + "databaseName=MyDatabase;"
                     + "integratedSecurity=true;";

This tells the driver to use the Windows credentials of the currently logged-in user for authentication.

Connecting with the JDBC Driver

To use the connection string in a Java application, you’ll need to load the SQL Server JDBC driver and establish a connection. Below is a full example of a Java program that connects to SQL Server using JDBC:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class SQLServerConnection {
    public static void main(String[] args) {
        String connectionUrl = "jdbc:sqlserver://localhost:1433;"
                             + "databaseName=MyDatabase;"
                             + "user=myUsername;"
                             + "password=myPassword;";

        try {
            // Load the SQL Server JDBC driver
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

            // Establish the connection
            Connection con = DriverManager.getConnection(connectionUrl);

            // Create and execute a basic SQL query
            String SQL = "SELECT * FROM Customers";
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(SQL);

            // Iterate through the result set and print the data
            while (rs.next()) {
                System.out.println(rs.getString("CustomerID") + " - " + rs.getString("CustomerName"));
            }

            // Close the resources
            rs.close();
            stmt.close();
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Expected Output:

Assuming you have a Customers table in your database, running the above code will output the customer IDs and names like so:

1 - John Doe
2 - Jane Smith
3 - Alice Johnson

Common Connection String Parameters

Property Description
databaseName Name of the database to connect to.
user Username for SQL Server login.
password Password for SQL Server login.
integratedSecurity If true, enables Windows authentication.
encrypt If true, forces encryption for the connection.
trustServerCertificate If true, trusts the SQL Server certificate without validation.

Troubleshooting Connection Issues

Invalid Connection URL

If you encounter an error like:

com.microsoft.sqlserver.jdbc.SQLServerException: The connection string contains a badly formed name or value.

Check that the connection string follows the correct format and that no semicolons (;) or equals signs (=) are misplaced.

Port Not Listening

If you get an error indicating that the connection was refused, ensure that:

  • The SQL Server instance is running.
  • The specified port is open and listening.

You can check which port SQL Server is listening on by running this query in SQL Server:

SELECT DISTINCT local_net_address, local_tcp_port 
FROM sys.dm_exec_connections
WHERE local_net_address IS NOT NULL;

Driver Not Found

If you see an error like:

java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver

Ensure that you have added the SQL Server JDBC driver to your project’s classpath. You can download the driver from Microsoft’s website.

Conclusion

Setting up a JDBC connection to SQL Server is straightforward once you understand the structure of the connection string. This tutorial has covered the essentials, including basic and advanced connection strings, how to integrate the connection string into a Java application, and some common troubleshooting tips.

Beekeeper Studio Is A Free & Open Source Database GUI

Best SQL query & editor tool I have ever used. It provides everything I need to manage my database. - ⭐⭐⭐⭐⭐ Mit

Beekeeper Studio is fast, intuitive, and easy to use. Beekeeper supports loads of databases, and works great on Windows, Mac and Linux.

Beekeeper's Linux version is 100% full-featured, no cut corners, no feature compromises.