此 Microsoft JDBC Driver for SQL Server 示例应用程序说明了如何从 SQL Server 数据库中检索一组数据,然后将这些数据显示出来。

此示例的代码文件名为 retrieveRS.java,可在以下位置找到该文件:

<安装目录>\sqljdbc_<版本>\<语言>\help\samples\resultsets

要求

若要运行此示例应用程序,必须将 classpath 设置为包含 sqljdbc.jar 文件或 sqljdbc4.jar 文件。如果 classpath 缺少 sqljdbc.jar 项或 sqljdbc4.jar 项,示例应用程序将引发“找不到类”的常见异常。还需要访问 SQL Server 2005 AdventureWorks 示例数据库。有关如何设置 classpath 的详细信息,请参阅使用 JDBC Driver

Microsoft JDBC Driver for SQL Server 提供两个类库文件:sqljdbc.jar 和 sqljdbc4.jar,具体使用哪个文件取决于首选的 Java 运行时环境 (JRE) 设置。有关选择哪个 JAR 文件的详细信息,请参阅 JDBC Driver 的系统要求

示例

在下面的示例中,示例代码将建立与 AdventureWorks 示例数据库的连接。然后,该代码通过对 SQLServerStatement 对象使用 SQL 语句,运行该 SQL 语句,并将其返回的数据放入 SQLServerResultSet 对象中。

接下来,示例代码调用自定义的 displayRow 方法来遍历结果集中包含的数据行,并使用 getString 方法显示其中包含的某些数据。

import java.sql.*;

public class retrieveRS {

   public static void main(String[] args) {

      // Create a variable for the connection string.
      String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
            "databaseName=AdventureWorks;integratedSecurity=true;";

      // Declare the JDBC objects.
      Connection con = null;
      Statement stmt = null;
      ResultSet rs = null;

      try {

         // Establish the connection.
         Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
         con = DriverManager.getConnection(connectionUrl);

         // Create and execute an SQL statement that returns a
         // set of data and then display it.
         String SQL = "SELECT * FROM Production.Product;";
         stmt = con.createStatement();
         rs = stmt.executeQuery(SQL);
         displayRow("PRODUCTS", rs);
      }

      // Handle any errors that may have occurred.
      catch (Exception e) {
         e.printStackTrace();
      }

      finally {
         if (rs != null) try { rs.close(); } catch(Exception e) {}
         if (stmt != null) try { stmt.close(); } catch(Exception e) {}
         if (con != null) try { con.close(); } catch(Exception e) {}
      }
   }

   private static void displayRow(String title, ResultSet rs) {
      try {
         System.out.println(title);
         while (rs.next()) {
            System.out.println(rs.getString("ProductNumber") + " : " + rs.getString("Name"));
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

请参阅