トッカンソフトウェア

JavaからJDBCでPostgreSQLにアクセス(プリペアードステートメント)

今回は、プリペアードステートメント(PreparedStatement)をやります。
これを使うことにより処理が少し早くなります。パフォーマンスが悪いときなどに使って下さい。


				
package javaPosgre;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class Posgre2 {
	public static void main(String[] args) {
		try {
			connectionTest();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

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

		try {

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

			// コネクションの取得
			conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "ps");

			// SELECTのテスト
			selectTest(conn);

			System.out.println("connectionTest_OK");

		} catch (Exception e) {

			System.out.println("connectionTest_NG");
			throw e;
		} finally {
			if (conn != null) {
				conn.close();
			}
		}
	}

	/**
	 * データ取得
	 * 
	 * @param conn
	 *            コネクション
	 * @throws SQLException
	 *             SQL例外
	 */
	public static void selectTest(Connection conn) throws SQLException {

		ResultSet rs = null;
		PreparedStatement ps = null;

		try {

			// ステートメントの作成
			ps = conn.prepareStatement("select * from m_user where id=? or id like ?");

			// 条件セット(1~)
			ps.setString(1, "0001");

			// Likeの場合、%を付ける
			ps.setString(2, "%2");

			// SELECTを実行する
			rs = ps.executeQuery();

			// 結果の表示
			while (rs.next()) {

				// データ取得(項目指定)
				System.out.println(rs.getString("id"));
			}

			System.out.println("selectTest_OK");
		} catch (Exception e) {
			System.out.println("selectTest_NG");
			throw e;
		} finally {
			if (rs != null) {
				rs.close();
				rs = null;
			}
			if (ps != null) {
				ps.close();
				ps = null;
			}
		}
	}
}


			


ステートメントの作成で実行するSQLを指定します。条件など変更がある部分は?を指定します。
				
// ステートメントの作成
ps = conn.prepareStatement("select * from m_user where id=? or id like ?");


			
条件のセットはサンプルではsetStringを使いましたが、項目の型に合わせてsetInt、setLongなども使えます。
				
// 条件セット(1~)
ps.setString(1, "0001");

// Likeの場合、%を付ける
ps.setString(2, "%2");


			
SQLの実行はexecuteQueryメソッドを使います。
				
// SELECTを実行する
rs = ps.executeQuery();


			
SQL実行後は前回と同様の処理を行います。

INSERT、UPDATE、DELETEも同じように実行できます。実行時はexecuteUpdateを使用して下さい。
				
// INSERT、UPDATE、DELETEもを実行する
int ret = ps.executeUpdate();


			

ページのトップへ戻る