トッカンソフトウェア

JavaからJDBCでPostgreSQLにアクセス(INSERT、UPDATE、DELETE)

前章でコネクションを取得するところをやったので、今回はコネクションを使ってデータを取得します。


				
package javaPosgre;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
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のテスト
			insertTest(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 insertTest(Connection conn) throws SQLException {
		Statement stmt = null;

		try {

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

			// SQLの実行(update、deleteもexecuteUpdateメソッドでいけます)
			stmt.executeUpdate("insert into m_user(id,name) values('004','test user4');");

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


			

コネクションを取得するところは前々回にやったので、省略します。

INSERT(UPDATE、delete)を実行するにはまずコネクションからステートメントを作成します。
				
// ステートメントの作成
stmt = conn.createStatement();


			
次にSQLを実行します。
				
// SQLの実行
stmt.executeUpdate("insert into m_user(id,name) values('004','test user4')");


			
UPDATE、DELETEも同じように実行できます。

UPDATE
				
// SQLの実行
stmt.executeUpdate("update m_user set name='test user4' where id = '004'");


			

DELETE
				
// SQLの実行
stmt.executeUpdate("delete m_user where id = '004'");


			


ページのトップへ戻る