22 Eylül 2022 Perşembe

JDBC PGSimpleDataSource Sınıfı

Giriş
Şu satırı dahil ederiz
import org.postgresql.ds.PGSimpleDataSource;
PGXADataSource yazısına bakılabilir
Açıklaması şöyle
The PGSimpleDataSource, which is the default DataSource implementation in PostgreSQL, uses the underlying Driver to acquire a physical connection which establishes a TCP connection to the database server.
And when the close method is called on the JDBC Connection object, the underlying Socket and TCP connection are terminated.
Maven
Şöyle yaparız.
<dependency>
  <groupId>org.postgresql</groupId>
  <artifactId>postgresql</artifactId>
  <version>9.4-1200-jdbc4</version>
</dependency>
constructor
Örnek
şöyle yaparız
PGSimpleDataSource dataSource = new PGSimpleDataSource();
dataSource.setDatabaseName("high_performance_java_persistence");
dataSource.setServerName("localhost");
dataSource.setUser("postgres");
dataSource.setPassword("admin");
Örnek
Şöyle yaparız
import org.postgresql.ds.common.BaseDataSource;

PostgreSQLContainer container = ...;

BaseDataSource dataSource = new PGSimpleDataSource();
dataSource.setUrl(container.getJdbcUrl());
dataSource.setUser(container.getUsername());
dataSource.setPassword(container.getPassword());
dataSource.setDatabaseName(container.getDatabaseName());
Örnek
Şöyle yaparız
import org.postgresql.ds.PGSimpleDataSource;
import org.postgresql.ds.common.BaseDataSource;
import org.testcontainers.containers.PostgreSQLContainer;

import javax.sql.CommonDataSource;
import javax.sql.DataSource;

// PGSimpleDataSource is both javax.sql.DataSource and javax.sql.CommonDataSource
CommonDataSource createDataSource() {
  PostgreSQLContainer postgreSQLContainer = ...;

  BaseDataSource dataSource = new PGSimpleDataSource();
  dataSource.setUrl(postgreSQLContainer.getJdbcUrl());
  dataSource.setUser(postgreSQLContainer.getUsername());
  dataSource.setPassword(postgreSQLContainer.getPassword());
  dataSource.setDatabaseName(postgreSQLContainer.getDatabaseName());

  return dataSource;
}



Hiç yorum yok:

Yorum Gönder