JDBC ResultSet Example with the SQL Server Database |Video upload date:  · Duration: PT2M53S  · Language: EN

Compact guide to using JDBC ResultSet with SQL Server showing connection query iteration and resource cleanup for reliable Java database code

Quick overview

If you want to pull rows from SQL Server into a Java app without turning your database into a haunted house of leaked connections this guide is for you. We will cover the Microsoft JDBC driver, opening a connection, using PreparedStatement for safety and speed, iterating a ResultSet with typed getters, and cleaning up with try with resources so your connection pool does not cry.

Add the JDBC driver

Use Maven or Gradle in real projects. For quick demos you can drop the Microsoft JDBC jar on the classpath. The driver class is com.microsoft.sqlserver.jdbc.SQLServerDriver. Modern JVMs often do the driver auto registration but calling Class.forName is harmless if you like being explicit.

Open a connection

For development DriverManager.getConnection is fine. For production use a connection pool. Pools avoid frequent handshake overhead and prevent the slowdowns that sneak up like unpaid interns. A typical JDBC URL looks like this:

String url = "jdbc:sqlserver://localhost;databaseName=MyDb";
Connection conn = DriverManager.getConnection(url, "user", "pass");

Remember to prefer a pool such as HikariCP if you care about latency and not setting fire to the server during peak load.

Prepare and execute the query

Never concatenate user input into SQL. PreparedStatement avoids SQL injection and gives SQL Server a chance to reuse execution plans. Use parameter bindings and let the database worry about math and sadness.

Iterate the ResultSet

Move the cursor with rs.next and use typed getters like getInt getString getTimestamp. Using column labels improves readability and makes refactoring less painful than reading seismograph prints from an earthquake.

  • Use getInt for integers and getString for text
  • Prefer column labels over numeric indexes for clarity
  • Handle SQL NULLs with wasNull or use wrapper types like Integer when needed

Resource management and cleanup

Try with resources is your friend. Wrap Connection PreparedStatement and ResultSet in try with resources so everything gets closed even when exceptions happen. This prevents pool exhaustion and the mysterious errors that arrive at 2 a.m.

Example code

Here is a concise example that demonstrates the essentials. It is straightforward and avoids horror show practices.

public static void runQuery() throws Exception {
    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    String url = "jdbc:sqlserver://localhost;databaseName=MyDb";

    try (Connection conn = DriverManager.getConnection(url, "user", "pass");
         PreparedStatement ps = conn.prepareStatement("SELECT id, name, created_at FROM people WHERE active = ?")) {

        ps.setBoolean(1, true);

        try (ResultSet rs = ps.executeQuery()) {
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                java.sql.Timestamp created = rs.getTimestamp("created_at");
                // use the values as needed
            }
        }
    }
}

Notes about performance and safety

  • Use a connection pool in production to avoid creating connections for every request
  • Prefer PreparedStatement for parameterized queries to defend against injection and to let SQL Server reuse execution plans
  • Use typed getters to avoid casting surprises and to keep your code readable
  • Close everything or wrap it in try with resources so you are not paged in the middle of dinner

Recap

Add the Microsoft JDBC driver to your project open a connection or use a pool prepare queries with PreparedStatement iterate the ResultSet with typed getters and always clean up resources. Do that and your Java app will read SQL Server rows reliably and with far less drama than the alternative.

I know how you can get Azure Certified, Google Cloud Certified and AWS Certified. It's a cool certification exam simulator site called certificationexams.pro. Check it out, and tell them Cameron sent ya!

This is a dedicated watch page for a single video.