W3docs

How do I connect to a SQL Server 2008 database using JDBC?

To connect to a SQL Server database using JDBC, you will need to use the JDBC driver for SQL Server.

To connect to a SQL Server database using JDBC, you will need to use the JDBC driver for SQL Server. Here's an example of how you can use the JDBC driver to connect to a SQL Server database:

  1. Download the SQL Server JDBC driver from Microsoft's website
  2. Add the JDBC driver to your classpath (e.g., via Maven: com.microsoft.sqlserver:mssql-jdbc or Gradle: implementation 'com.microsoft.sqlserver:mssql-jdbc')
  3. Use the following code to establish a connection to the database

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JdbcExample {
    public static void main(String[] args) {
        String url = "jdbc:sqlserver://hostname:port;databaseName=dbname";
        String username = "user";
        String password = "pass";

        try (Connection conn = DriverManager.getConnection(url, username, password)) {
            System.out.println("Connected successfully!");
        } catch (SQLException e) {
            System.err.println("Failed to connect to the database.");
            e.printStackTrace();
        }
    }
}

Replace "hostname", "port", "dbname", "user", and "pass" with the appropriate values for your database.

Once you have established a connection to the database, you can execute SQL statements and process the results using the standard JDBC APIs.

I hope this helps! Let me know if you have any questions.