杰瑞科技汇

Java如何连接SQL Server?

Of course! Connecting Java to a SQL Server database is a very common task. Here’s a comprehensive guide covering everything you need to know, from the basic setup to best practices and troubleshooting.

Java如何连接SQL Server?-图1
(图片来源网络,侵删)

The Core Components

To connect Java to SQL Server, you need two main things:

  1. JDBC Driver: A library that acts as a bridge, allowing your Java application to "speak" the SQL Server protocol. Microsoft provides the official JDBC driver.
  2. Connection String: A special string of text that tells the JDBC driver which database server to connect to, what credentials to use, and other connection parameters.

Step-by-Step Guide

Step 1: Download the JDBC Driver

You need to get the official Microsoft JDBC Driver for SQL Server.

  1. Go to the official download page: Microsoft JDBC Driver for SQL Server
  2. Choose the version that matches your Java and SQL Server versions.
  3. Download the ZIP file.
  4. Extract the ZIP file. Inside, you'll find a .jar file (e.g., mssql-jdbc-12.4.2.jre11.jar). This is the driver file you need to add to your project.

Step 2: Add the Driver to Your Project

You need to include the JDBC driver's .jar file in your project's classpath. How you do this depends on your build tool.

Using Maven (Recommended):

Java如何连接SQL Server?-图2
(图片来源网络,侵删)

Add the dependency to your pom.xml file. Choose the appropriate <scope> (e.g., runtime).

<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>mssql-jdbc</artifactId>
    <version>12.4.2.jre11</version> <!-- Use the latest version -->
    <scope>runtime</scope>
</dependency>

Using Gradle:

Add the dependency to your build.gradle file.

implementation 'com.microsoft.sqlserver:mssql-jdbc:12.4.2.jre11' // Use the latest version

Manual Setup (Without a Build Tool):

Java如何连接SQL Server?-图3
(图片来源网络,侵删)
  1. Place the downloaded .jar file in a dedicated lib folder in your project.
  2. If you are compiling from the command line, use the -cp (classpath) flag:
    javac -cp ".;path/to/your/mssql-jdbc-12.4.2.jre11.jar" YourJavaFile.java
  3. When running your application, you must also include the jar in the classpath:
    java -cp ".;path/to/your/mssql-jdbc-12.4.2.jre11.jar" YourJavaFile

    Note: On Linux or macOS, the separator is instead of .

Step 3: Write the Java Code

Here is a complete, commented example demonstrating how to connect, execute a query, and process the results.

Example: DatabaseExample.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DatabaseExample {
    // --- Connection Details ---
    // Replace with your actual database details
    private static final String DB_URL = "jdbc:sqlserver://localhost:1433;databaseName=YourDatabase;encrypt=true;trustServerCertificate=true";
    private static final String USER = "your_username";
    private static final String PASS = "your_password";
    public static void main(String[] args) {
        // Using try-with-resources to ensure the connection is closed automatically
        try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS)) {
            if (conn != null) {
                System.out.println("Connected to the database successfully!");
                // Uncomment the method you want to run
                // selectData(conn);
                // insertData(conn);
            }
        } catch (SQLException e) {
            System.err.println("Database connection or query failed!");
            e.printStackTrace();
        }
    }
    /**
     * Demonstrates how to execute a SELECT query and process the results.
     */
    public static void selectData(Connection conn) throws SQLException {
        String sql = "SELECT id, name, email FROM users";
        // Using try-with-resources for Statement and ResultSet
        try (Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            System.out.println("\n--- User List ---");
            while (rs.next()) {
                // Retrieve by column name for robustness
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String email = rs.getString("email");
                // Display values
                System.out.printf("ID: %d, Name: %s, Email: %s%n", id, name, email);
            }
        }
    }
    /**
     * Demonstrates how to execute an INSERT query using a PreparedStatement (safer).
     */
    public static void insertData(Connection conn) throws SQLException {
        String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            // Set parameters (prevents SQL injection)
            pstmt.setString(1, "John Doe");
            pstmt.setString(2, "john.doe@example.com");
            int affectedRows = pstmt.executeUpdate();
            System.out.println("\nInserted " + affectedRows + " row(s) into the users table.");
        }
    }
}

Connection String Breakdown

The connection string is crucial. Let's break down the example:

jdbc:sqlserver://localhost:1433;databaseName=YourDatabase;encrypt=true;trustServerCertificate=true;

  • jdbc:sqlserver://: The protocol and sub-protocol. This tells the JDBC driver to use the SQL Server driver.
  • localhost: The hostname or IP address of your SQL Server instance.
  • 1433: The port number SQL Server is listening on. The default is 1433.
  • ;databaseName=YourDatabase: The name of the specific database you want to connect to.
  • ;encrypt=true: (Recommended) Enables SSL encryption for the data.
  • ;trustServerCertificate=true: (Use with caution) This is a development-only setting that tells the driver to trust any SSL certificate presented by the server, even if it's self-signed or invalid. Do not use this in production. In production, you should provide the correct CA certificate.

Other Common Parameters:

  • user=your_username: Specifies the database user.
  • password=your_password: Specifies the user's password.
  • integratedSecurity=true: Uses Windows Authentication (trusted connection) instead of a username and password. The string would look like: jdbc:sqlserver://localhost;databaseName=YourDatabase;integratedSecurity=true;

Best Practices

  1. Use try-with-resources: Always wrap Connection, Statement, PreparedStatement, and ResultSet in try-with-resources blocks. This ensures they are closed automatically, preventing resource leaks.

    // Good
    try (Connection conn = DriverManager.getConnection(...)) {
        // ...
    }
    // Also good for nested resources
    try (PreparedStatement pstmt = conn.prepareStatement(...);
         ResultSet rs = pstmt.executeQuery()) {
        // ...
    }
  2. Use PreparedStatement for Queries: Whenever your query includes variables (especially from user input), use PreparedStatement. It:

    • Prevents SQL Injection: It separates the SQL command from the data.
    • Improves Performance: The database can cache the execution plan for the query.
  3. Don't Hardcode Credentials: For any real application, avoid putting usernames and passwords directly in your code. Use environment variables, configuration files (like config.properties), or a secrets management system.

    Example using a config.properties file: config.properties:

    db.url=jdbc:sqlserver://localhost:1433;databaseName=YourDatabase
    db.user=your_username
    db.password=your_password

    DatabaseExample.java:

    import java.io.InputStream;
    import java.util.Properties;
    // ...
    Properties props = new Properties();
    try (InputStream input = DatabaseExample.class.getClassLoader().getResourceAsStream("config.properties")) {
        if (input == null) {
            System.err.println("Sorry, unable to find config.properties");
            return;
        }
        props.load(input);
    }
    String DB_URL = props.getProperty("db.url");
    String USER = props.getProperty("db.user");
    String PASS = props.getProperty("db.password");
  4. Use a Connection Pool: In a web application or any application that makes frequent database connections, creating a new connection for every request is very slow. A connection pool (like HikariCP, Apache DBCP, or Tomcat JDBC) maintains a cache of open connections that can be reused.

    Example with HikariCP (Maven dependency):

    <dependency>
        <groupId>com.zaxxer</groupId>
        <artifactId>HikariCP</artifactId>
        <version>5.0.1</version>
    </dependency>
    import com.zaxxer.hikari.HikariConfig;
    import com.zaxxer.hikari.HikariDataSource;
    // ...
    HikariConfig config = new HikariConfig();
    config.setJdbcUrl("jdbc:sqlserver://...");
    config.setUsername("...");
    config.setPassword("...");
    HikariDataSource ds = new HikariDataSource(config);
    try (Connection conn = ds.getConnection()) {
        // Use the connection...
    }

Troubleshooting Common Issues

  • ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver

    • Cause: The JDBC driver .jar file is not in your project's classpath.
    • Solution: Double-check that you have added the dependency correctly in your pom.xml/build.gradle or manually included the .jar file.
  • NetworkError: Connection refused: connect or The TCP/IP connection to the host has failed

    • Cause: Java cannot reach the SQL Server machine on the specified port.
    • Solution:
      1. Verify the server address (localhost or IP) is correct.
      2. Verify the port number is correct (default is 1433).
      3. Make sure SQL Server is running.
      4. Check your firewall to ensure it's not blocking port 1433.
  • Login failed for user '...'

    • Cause: The username or password is incorrect.
    • Solution: Double-check your credentials. If using Windows Authentication (integratedSecurity=true), ensure the Java process is running under a user account that has access to the SQL Server.
  • The driver could not establish a secure connection to SQL Server due to authentication failure

    • Cause: This often happens when encrypt=true is set, but the server's certificate cannot be validated. This is common with self-signed certificates in development.
    • Solution (for development only): Add trustServerCertificate=true to your connection string, as shown in the example. For production, you must configure the driver to trust the correct Certificate Authority (CA).
分享:
扫描分享到社交APP
上一篇
下一篇