此 Microsoft SQL Server 2005 JDBC Driver 範例應用程式示範如何使用連接 URL 來連接到 SQL Server 資料庫。它也示範如何使用 SQL 陳述式,從 SQL Server 資料庫擷取資料。
此範例的程式碼檔案名稱為 connectURL.java,可以在下列位置找到它:
<安裝目錄>\sqljdbc_<版本>\<語言>\help\samples\connections
需求
若要執行此範例應用程式,您必須設定 Classpath 以包括 sqljdbc.jar 檔。如果 Classpath 遺漏 sqljdbc.jar 的項目,範例應用程式將會擲出「找不到類別」的一般例外狀況。您也需要對 SQL Server 2000 AdventureWorks 範例資料庫具有存取權。
如需如何設定 Classpath 的詳細資訊,請參閱<使用 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) {}
}
}
}