Java8 JDBCでPostgreSQLにアクセス、操作(INSERT、UPDATE、DELETE)サンプル

環境
Windows 10
PostgreSQL 9.6
Java 1.8
Eclipse 4.14

構成
JDBCドライバ
postgresql-42.6.0.jar

ダウンロードサイト
https://jdbc.postgresql.org/

jarファイルを追加します
1.プロジェクトを右クリックして「プロパティ(R)」をクリックします。
2.左側の「ビルド・パス」を選択します。
3.「ライブラリー」タブの「外部JAR追加」を選択し、ダウンロードたPostgreSQL JDBCを追加する。

説明
1.PostgreSQLへの接続
jdbc:postgresql://<接続先DBサーバのIP or ホスト名>:<DBのポート番号>/<DB名>;

2. DriverManager.getConnection(データベースのURL, データベースのUSER, データベースのPWD);データベースのコネクションを取得します。

3. executeQuery(SQL文字列)
SELECT文の結果受け取りには「ResultSet」クラスが使われます。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
4.executeUpdate(SQL文字列);
SQL文を実行します。 自動コミットがOFFの場合、commit()メソッドによりコミットします。
4.executeUpdate(SQL文字列); SQL文を実行します。 自動コミットがOFFの場合、commit()メソッドによりコミットします。
4.executeUpdate(SQL文字列);
SQL文を実行します。 自動コミットがOFFの場合、commit()メソッドによりコミットします。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class PostgreDemo {
// 接続文字列 IP/ホスト名:DBのポート番号/DB名
private final static String URL = "jdbc:postgresql://127.0.0.1:5432/tpesPT";
// ユーザー名
private final static String USER = "tpes";
// パスワード
private final static String PWD = "tpes";
public static void main(String[] args) {
try {
connTest();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* コネクションの取得
*
* @throws Exception 実行時例外
*/
public static void connTest() throws Exception {
Connection conn = null;
try {
// クラスのロード
Class.forName("org.postgresql.Driver");
// コネクションの取得
conn = DriverManager.getConnection(URL, USER, PWD);
// SELECTのSQL構文の実行します
insertTest(conn);
System.out.println("PostgreSQLに接続成功です");
} catch (Exception e) {
System.out.println("PostgreSQLに接続失敗です");
throw e;
} finally {
if (conn != null) {
conn.close();
}
}
}
/**
* データを挿入(insert)
*
* @param conn コネクション
* @throws SQLException SQL例外
*/
public static void insertTest(Connection conn) throws SQLException {
Statement stmt = null;
try {
// ステートメントの作成
stmt = conn.createStatement();
// SQLの実行(update、deleteもexecuteUpdateメソッドでいけます)
stmt.executeUpdate("insert into test_tbl(uid,uname) values('2002','東京');");
System.out.println("挿入成功");
} catch (Exception e) {
System.out.println("挿入失敗");
throw e;
} finally {
if (stmt != null) {
stmt.close();
stmt = null;
}
}
}
}
package com.arkgame.study; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class PostgreDemo { // 接続文字列 IP/ホスト名:DBのポート番号/DB名 private final static String URL = "jdbc:postgresql://127.0.0.1:5432/tpesPT"; // ユーザー名 private final static String USER = "tpes"; // パスワード private final static String PWD = "tpes"; public static void main(String[] args) { try { connTest(); } catch (Exception e) { e.printStackTrace(); } } /** * コネクションの取得 * * @throws Exception 実行時例外 */ public static void connTest() throws Exception { Connection conn = null; try { // クラスのロード Class.forName("org.postgresql.Driver"); // コネクションの取得 conn = DriverManager.getConnection(URL, USER, PWD); // SELECTのSQL構文の実行します insertTest(conn); System.out.println("PostgreSQLに接続成功です"); } catch (Exception e) { System.out.println("PostgreSQLに接続失敗です"); throw e; } finally { if (conn != null) { conn.close(); } } } /** * データを挿入(insert) * * @param conn コネクション * @throws SQLException SQL例外 */ public static void insertTest(Connection conn) throws SQLException { Statement stmt = null; try { // ステートメントの作成 stmt = conn.createStatement(); // SQLの実行(update、deleteもexecuteUpdateメソッドでいけます) stmt.executeUpdate("insert into test_tbl(uid,uname) values('2002','東京');"); System.out.println("挿入成功"); } catch (Exception e) { System.out.println("挿入失敗"); throw e; } finally { if (stmt != null) { stmt.close(); stmt = null; } } } }
package com.arkgame.study;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class PostgreDemo {

      // 接続文字列 IP/ホスト名:DBのポート番号/DB名
      private final static String URL = "jdbc:postgresql://127.0.0.1:5432/tpesPT";
      // ユーザー名
      private final static String USER = "tpes";
      // パスワード
      private final static String PWD = "tpes";

      public static void main(String[] args) {

            try {
                  connTest();
            } catch (Exception e) {
                  e.printStackTrace();
            }
      }

      /**
       * コネクションの取得
       * 
       * @throws Exception 実行時例外
       */
      public static void connTest() throws Exception {
            Connection conn = null;

            try {

                  // クラスのロード
                  Class.forName("org.postgresql.Driver");

                  // コネクションの取得
                  conn = DriverManager.getConnection(URL, USER, PWD);

                  // SELECTのSQL構文の実行します
                  insertTest(conn);

                  System.out.println("PostgreSQLに接続成功です");
            } catch (Exception e) {
                  System.out.println("PostgreSQLに接続失敗です");
                  throw e;
            } finally {
                  if (conn != null) {
                        conn.close();
                  }
            }
      }

      /**
       * データを挿入(insert)
       * 
       * @param conn コネクション
       * @throws SQLException SQL例外
       */
      public static void insertTest(Connection conn) throws SQLException {
            Statement stmt = null;

            try {
                  // ステートメントの作成
                  stmt = conn.createStatement();

                  // SQLの実行(update、deleteもexecuteUpdateメソッドでいけます)
                  stmt.executeUpdate("insert into test_tbl(uid,uname) values('2002','東京');");

                  System.out.println("挿入成功");
            } catch (Exception e) {
                  System.out.println("挿入失敗");
                  throw e;
            } finally {
                  if (stmt != null) {
                        stmt.close();
                        stmt = null;
                  }
            }
      }
}

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
コンソール画面に下記メッセージを出力します
挿入成功
PostgreSQLに接続成功です
テーブル「test_tbl」に「2002,'東京'」レコードを挿入しました。
コンソール画面に下記メッセージを出力します 挿入成功 PostgreSQLに接続成功です テーブル「test_tbl」に「2002,'東京'」レコードを挿入しました。
コンソール画面に下記メッセージを出力します
挿入成功
PostgreSQLに接続成功です
テーブル「test_tbl」に「2002,'東京'」レコードを挿入しました。

 

Java

Posted by arkgame