🧚 주목! Beekeeper Studio는 빠르고 현대적이며 오픈 소스 데이터베이스 GUI입니다 다운로드
September 23, 2024 작성자: 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.).

If you’re working with PostgreSQL, check out our PostgreSQL JDBC URL Builder to easily construct connection strings.

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는 무료 & 오픈 소스 데이터베이스 GUI입니다

제가 사용해 본 최고의 SQL 쿼리 & 편집기 도구입니다. 데이터베이스 관리에 필요한 모든 것을 제공합니다. - ⭐⭐⭐⭐⭐ Mit

Beekeeper Studio는 빠르고 직관적이며 사용하기 쉽습니다. Beekeeper는 많은 데이터베이스를 지원하며 Windows, Mac, Linux에서 훌륭하게 작동합니다.

Beekeeper의 Linux 버전은 100% 완전한 기능을 갖추고 있으며, 기능 타협이 없습니다.

사용자들이 Beekeeper Studio에 대해 말하는 것

★★★★★
"Beekeeper Studio는 제 예전 SQL 워크플로를 완전히 대체했습니다. 빠르고 직관적이며 데이터베이스 작업을 다시 즐겁게 만들어 줍니다."
— Alex K., 데이터베이스 개발자
★★★★★
"많은 데이터베이스 GUI를 사용해 봤지만, Beekeeper는 기능과 단순함 사이의 완벽한 균형을 찾았습니다. 그냥 작동합니다."
— Sarah M., 풀스택 엔지니어

SQL 워크플로를 개선할 준비가 되셨나요?

download 무료 다운로드