PostgreSQL提供了应用可以直接使用的两种DataSource实现。一种是充当连接池,另外一种不使用任何 pooling
而只是简单的通过 DataSource 接口提供访问数据库的连接。 此外, 除非应用服务器不支持
ConnectionPoolDataSource 接口,否则这些实现能在应用服务器环境中使用。
下面列出一个例子,供参考。
而只是简单的通过 DataSource 接口提供访问数据库的连接。 此外, 除非应用服务器不支持
ConnectionPoolDataSource 接口,否则这些实现能在应用服务器环境中使用。
下面列出一个例子,供参考。
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.postgresql.ds.PGPoolingDataSource;
public class Demo2 {
public static void main(String args[]){
PGPoolingDataSource source = new PGPoolingDataSource();
source.setDataSourceName("First Source");
source.setServerName("localhost");
source.setDatabaseName("mydb_1");
source.setUser("postgres");
source.setPassword("1234");
source.setMaxConnections(10);
String sql = "insert into students (id,name) values(?,?)";
Connection conn = null;
try {
conn = source.getConnection();
PreparedStatement pstmt=conn.prepareStatement(sql);
pstmt.setInt(1,1226);
pstmt.setString(2,"Gogo_yeyue");
pstmt.executeUpdate();
pstmt.close();
// use connection
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null) {
try { conn.close(); } catch (SQLException e) {}
}
}
}
}