11.3 应用:DataSource

    PostgreSQL 包含两个DataSource的实现,如表11.2 "DataSource Implementations"所示,一个作为连接池,而另一个不是。连接池的实现在客户端调用close方法时实际上并不关闭连接,而是把连接返回到一个可用的连接池给其他客户端使用。这样就避免了任何重复打开和关闭连接造成的开销,并且允许大量的客户端分享少量的数据库连接。

     这里提供的不是世上最富有特性的数据源连接池实现。在其他类型中,连接在池本身关闭之前永远不会关闭,也没有缩小连接池的办法。还不如,除了缺省配置用户,其他用户的连接请求不要放在池中。它的错误处理有时不能从池中删除坏掉的连接。一般不推荐使用PostgreSQL提供的连接池。检查应用服务器或者检出jakarta commons DBCP这个极好的项目

表 11.2. DataSource 实现
 
Pooling Implementation Class
No org.postgresql.ds.PGSimpleDataSource
Yes org.postgresql.ds.PGPoolingDataSource

    两种实现使用同样的配置模式。JDBC 要求 DataSource 通过 JavaBean 属性配置, 在表11.3里列出。 因此每种这个属性都有获取和设置属性的方法。
表11.3. DataSource 配置属性
 
Property Type Description
serverName String PostgreSQL? database server host name
databaseName String PostgreSQL? database name
portNumber int TCP port which the PostgreSQL? database server is listening on (or 0 to use the default port)
user String User used to make database connections

    连接池实现要求一些额外的配置属性,如表11.4所示:
表 11.4. 额外的DataSource连接池配置属性
 
Property Type Description
dataSourceName String Every pooling DataSource must have a unique name.
initialConnections int The number of database connections to be created when the pool is initialized.
maxConnections int The maximum number of open database connections to allow. When more connections are requested, the caller will hang until a connection is returned to the pool.

===============================================================================
 
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM mytable WHERE columnfoo = 500");
while (rs.next()) {
    System.out.print("Column 1 returned ");
    System.out.println(rs.getString(1));
}
rs.close();
st.close();