要直接从 Java™ Platform, Enterprise Edition (Java EE) 应用程序客户机中访问数据库,需要从客户机部署描述符中配置的资源引用中检索
javax.sql.DataSource 对象。此资源引用是作为客户机应用程序的部署描述符的组成部分配置的,并提供对预先配置的数据源对象的引用。
关于此任务
注意,从应用程序客户机的数据访问使用直接来自客户机端的 JDBC 驱动程序连接功能。它不利用可用于应用程序服务器运行时的其他合用支持。为此,您的客户机应用程序应该利用在服务器端运行的企业 Bean 执行数据访问。然后此企业 Bean 可利用产品运行时提供的连接复用及其他增加的功能。
过程
- 导入相应的 JDBC API 和命名包:
import java.sql.*;
import javax.sql.*;
import javax.naming.*;
- 创建初始命名上下文:
InitialContext ctx = new InitialContext();
- 使用 InitialContext 对象从资源引用中查找数据源对象。
javax.sql.DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/myDS");
//where jdbc/myDS is the name of the resource reference
- 从数据源中获取 java.sql.Connection。
- 将来的某一步骤中在 Application Client Resource Configuration Tool (ACRCT) 中创建数据源时,如果连接不需要用户标识和密码,或者如果您将使用指定的 defaultUser 和 defaultPassword,使用此方法:
java.sql.Connection conn = ds.getConnection();
- 否则,您应该用特定用户标识和密码进行连接:
java.sql.Connection conn = ds.getConnection("user", "password");
//where user and password are the user id and password for the connection
- 相应地使用 java.sql.Statement、java.sql.PreparedStatement 或 java.sql.CallableStatement 接口运行数据库查询。
Statement stmt = conn.createStatement();
String query = "Select FirstNme from " + owner.toUpperCase() + ".Employee where LASTNAME = '" + searchName + "'";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) { firstNameList.addElement(rs.getString(1));
}
- 关闭前一个步骤中使用的数据库对象,包含任何 ResultSet、Statement、PreparedStatement 或 CallableStatement 对象。
- 关闭连接。 理论上,应该在回绕数据库操作的 try...catch 语句的一个 finally 块中关闭连接。此操作确保万一发生异常,连接也得以关闭。
conn.close();