JDBCドライバーを使用してPostgreSQLに接続する
JDBCドライバーを使用してPostgreSQLデータベースに接続する方法を示すJDBCの例。
でテスト済み:
-
Java 8
-
PostgreSQL 11
-
PostgreSQL JDBCドライバー42.2.5
1. PostgreSQL JDBCドライバーのダウンロード
http://jdbc.postgresql.org/download.htmlにアクセスして、最新のPostgreSQLJDBCドライバーをダウンロードします。
2. JDBC接続
2.1 Make a connection to the PostgreSQL database.
JDBCExample.java
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class JDBCExample { public static void main(String[] args) { // https://docs.oracle.com/javase/8/docs/api/java/sql/package-summary.html#package.description // auto java.sql.Driver discovery -- no longer need to load a java.sql.Driver class via Class.forName // register JDBC driver, optional, since java 1.6 /*try { Class.forName("org.postgresql.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); }*/ // auto close connection try (Connection conn = DriverManager.getConnection( "jdbc:postgresql://127.0.0.1:5432/test", "postgres", "password")) { if (conn != null) { System.out.println("Connected to the database!"); } else { System.out.println("Failed to make connection!"); } } catch (SQLException e) { System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage()); } catch (Exception e) { e.printStackTrace(); } } }
出力、ドライバーなし?
> javac JDBCExample.java > java JDBCExample SQL State: 08001 No suitable driver found for jdbc:postgresql://127.0.0.1:5432/test
java
コマンドで実行するには、PostgreSQLJDBCドライバーを手動でロードする必要があります。 すべてがc:\db
フォルダーに格納されていると想定し、-cp
オプションを指定して再実行します。
> java -cp "c:\db\postgresql-42.2.5.jar;c:\db" JDBCExample Connected to the database!
3. メーベン
PostgreSQL JDBCドライバーは、Maven中央リポジトリで利用可能です。
pom.xml
org.postgresql postgresql 42.2.5
4. JDBC Select
4.1 Another JDBC example to get all rows from a table.
JDBCExample2.java
package com.example.jdbc; import com.example.jdbc.model.Employee; import java.math.BigDecimal; import java.sql.*; import java.util.ArrayList; import java.util.List; public class JDBCExample2 { public static void main(String[] args) { Listresult = new ArrayList<>(); String SQL_SELECT = "Select * from EMPLOYEE"; // auto close connection and preparedStatement try (Connection conn = DriverManager.getConnection( "jdbc:postgresql://127.0.0.1:5432/test", "postgres", "password"); PreparedStatement preparedStatement = conn.prepareStatement(SQL_SELECT)) { ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { long id = resultSet.getLong("ID"); String name = resultSet.getString("NAME"); BigDecimal salary = resultSet.getBigDecimal("SALARY"); Timestamp createdDate = resultSet.getTimestamp("CREATED_DATE"); Employee obj = new Employee(); obj.setId(id); obj.setName(name); obj.setSalary(salary); // Timestamp -> LocalDateTime obj.setCreatedDate(createdDate.toLocalDateTime()); result.add(obj); } result.forEach(x -> System.out.println(x)); } catch (SQLException e) { System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage()); } catch (Exception e) { e.printStackTrace(); } } }
Employee.java
package com.example.jdbc.model; import java.math.BigDecimal; import java.time.LocalDateTime; public class Employee { private Long id; private String name; private BigDecimal salary; private LocalDateTime createdDate; //... }
テーブル定義。
CREATE TABLE EMPLOYEE ( ID serial, NAME varchar(100) NOT NULL, SALARY numeric(15, 2) NOT NULL, CREATED_DATE timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP PRIMARY KEY (ID) );
ソースコードをダウンロード
$ git clone https://github.com/example/java-jdbc.git