这是我的 jboss/deploy/postgres-ds.xml 文件。此处给出了连接 url、用户名和密码。如何在我的 servlet 中获得到该数据库的连接。
<local-tx-datasource>
<jndi-name>PostgresDS</jndi-name>
<connection-url>jdbc:postgresql://localhost:5432/postgres</connection-url>
<driver-class>org.postgresql.Driver</driver-class>
<user-name>postgres</user-name>
<password>qwerty</password>
<!-- sql to call when connection is created
<new-connection-sql>some arbitrary sql</new-connection-sql>
-->
<!-- sql to call on an existing pooled connection when it is obtained from pool
<check-valid-connection-sql>some arbitrary sql</check-valid-connection-sql>
-->
<!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml (optional) -->
</local-tx-datasource>
我是否应该在每个 servlet 中获得这样的连接:
Connection conn =null; // Create connection object
String database = "postgres"; // Name of database
String user = "postgres"; //
String password = "qwerty";
String url = "jdbc:postgresql://localhost:5432/" + database;
ResultSet rs = null;
ResultSetMetaData rsm = null;
try{
Class.forName("org.postgresql.Driver").newInstance();
//.newInstance()
} catch(Exception e)
{
System.err.println(e);
}
try{
conn = DriverManager.getConnection(url, user, password);
}catch(SQLException se)
{
System.err.println(se);
}
如果每次都必须这样做,那么为什么要在 postgres-ds.xml 文件中提供 url、用户名和密码呢?