在JBoss中获取与数据库的连接?

sur*_*raj 3 java postgresql jboss servlets

这是我的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>
Run Code Online (Sandbox Code Playgroud)

我应该在每个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);
}
Run Code Online (Sandbox Code Playgroud)

如果必须每次都这样做,那么为什么要在postgres-ds.xml文件中提供url,用户名和密码?

Sat*_*tya 7

您可以使用DataSource来获取Connection

javax.naming.Context ic = new javax.naming.InitialContext();
javax.naming.Context ctx = (javax.naming.Context) ic.lookup("java:");
javax.sql.DataSource ds = (javax.sql.DataSource) ctx.lookup("PostgresDS");
java.sql.Connection con = ds.getConnection();
Run Code Online (Sandbox Code Playgroud)

  • 从系统的角度来看,"不,不一定".通过JDBC连接使用DS的另一个好处是,使用DS可以利用应用服务器的连接池. (2认同)