此 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);
}
}
}