共用方式為


資料來源範例

此 Microsoft SQL Server 2005 JDBC Driver 範例應用程式示範如何使用資料來源物件來連接到 SQL Server 資料庫。它也示範如何使用預存程序,從 SQL Server 資料庫擷取資料。

此範例的程式碼檔案名稱為 connectDS.java,可以在下列位置找到它:

<安裝目錄>\sqljdbc_<版本>\<語言>\help\samples\connections

需求

若要執行此範例應用程式,您必須設定 Classpath 以包括 sqljdbc.jar 檔。如果 Classpath 遺漏 sqljdbc.jar 的項目,範例應用程式將會擲出「找不到類別」的一般例外狀況。您也需要對 SQL Server 2000 AdventureWorks 範例資料庫具有存取權。

如需如何設定 Classpath 的詳細資訊,請參閱<使用 JDBC 驅動程式>。

範例

在下列範例中,範例程式碼會使用 SQLServerDataSource 物件的 setter 方法設定各種連接屬性,然後呼叫 SQLServerDataSource 物件的 getConnection 方法,傳回 SQLServerConnection 物件。

接著,範例程式碼會使用 SQLServerConnection 物件的 prepareCall方法建立 SQLServerCallableStatement 物件,然後呼叫 executeQuery 方法來執行預存程序。

最後,範例會使用從 executeQuery 方法傳回的 SQLServerResultSet 物件,重複執行預存程序所傳回的結果。

import java.sql.*;
import com.microsoft.sqlserver.jdbc.*;

public class connectDS {

   public static void main(String[] args) {

      // Declare the JDBC objects.
      Connection con = null;
      CallableStatement cstmt = null;
      ResultSet rs = null;

      try {
         // Establish the connection. 
         SQLServerDataSource ds = new SQLServerDataSource();
         ds.setUser("UserName");
         ds.setPassword("*****");
         ds.setServerName("localhost");
         ds.setPortNumber(1433); 
         ds.setDatabaseName("AdventureWorks");
         con = ds.getConnection();

         // Execute a stored procedure that returns some data.
         cstmt = con.prepareCall("{call dbo.uspGetEmployeeManagers(?)}");
         cstmt.setInt(1, 50);
         rs = cstmt.executeQuery();

         // Iterate through the data in the result set and display it.
         while (rs.next()) {
            System.out.println("EMPLOYEE: " + rs.getString("LastName") + 
               ", " + rs.getString("FirstName"));
            System.out.println("MANAGER: " + rs.getString("ManagerLastName") + 
               ", " + rs.getString("ManagerFirstName"));
            System.out.println();
         }
      }

      // Handle any errors that may have occurred.
      catch (Exception e) {
         e.printStackTrace();
      }
      finally {
         if (rs != null) try { rs.close(); } catch(Exception e) {}
         if (cstmt != null) try { cstmt.close(); } catch(Exception e) {}
         if (con != null) try { con.close(); } catch(Exception e) {}
         System.exit(1);
      }
   }
}

另請參閱

其他資源

連接及擷取資料