Pages

2011年8月13日 星期六

Microsoft JDBC 連接 URL 範例


在下列範例中,範例程式碼會在連接 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));
         }
         rs.close();
         rs = null;
         stmt.close();
         stmt = null;
         con.close();
         con = null;
      }

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

0 意見: