연결 URL 샘플

이 Microsoft SQL Server 2005 JDBC 드라이버 샘플 응용 프로그램에서는 연결 URL을 사용하여 SQL Server 데이터베이스에 연결하는 방법을 보여 줍니다. 또한 SQL 문을 사용하여 SQL Server 데이터베이스에서 데이터를 검색하는 방법도 보여 줍니다.

이 샘플의 코드 파일 이름은 connectURL.java이며 다음과 같은 위치에 있습니다.

<installation directory>\sqljdbc_<version>\<language>\help\samples\connections

요구 사항

이 샘플 응용 프로그램을 실행하려면 클래스 경로에 sqljdbc.jar 파일이 포함되도록 설정해야 합니다. 클래스 경로에 sqljdbc.jar 파일에 대한 항목이 없으면 샘플 응용 프로그램에서 "클래스를 찾을 수 없습니다." 예외가 발생합니다. 또한 SQL Server 2000 AdventureWorks 샘플 데이터베이스에 대한 액세스 권한이 필요합니다.

클래스 경로를 설정하는 방법에 대한 자세한 내용은 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) {}
      }
   }
}

참고 항목

관련 자료

데이터 연결 및 검색