此 Microsoft SQL Server JDBC Driver 示例应用程序演示了如何使用连接 URL 来连接 SQL Server 数据库。还说明了如何使用 SQL 语句从 SQL Server 数据库中检索数据。

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

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

要求

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

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

示例

在下面的实例中,示例代码在连接 URL 中设置了多个连接属性,然后调用 DriverManager 类的 getConnection 方法,以返回 SQLServerConnection 对象。

接下来,示例代码使用 SQLServerConnection 对象的 createStatement 方法来创建 SQLServerStatement 对象,然后调用 executeQuery 方法来执行 SQL 语句。

最后,示例代码使用 executeQuery 方法返回的 SQLServerResultSet 对象来遍历 SQL 语句返回的结果。

import java.sql.*;

public class connectURL {

   public static void main(String[] args) {

      // Create a variable for the connection string.
      String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
         "databaseName=AdventureWorks;user=UserName;password=*****";

      // 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 some data.
         String SQL = "SELECT TOP 10 * FROM Person.Contact";
         stmt = con.createStatement();
         rs = stmt.executeQuery(SQL);

         // Iterate through the data in the result set and display it.
         while (rs.next()) {
            System.out.println(rs.getString(4) + " " + rs.getString(6));
         }
      }

      // 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) {}
      }
   }
}

请参阅

连接和检索数据