0
0

【Java】初心者向け_データベースを操作するコード例(SELECT/UPDATE/INSERT/DELETE)

Posted at

目次

この記事は5分ほどで読めます。
1. この記事のターゲット層
2. 今回使用するテーブル
3. 4大命令
4. おわりに

1. この記事のターゲット層

「本などで学習したが、Javaからデータベースを操作する方法がよくわからなかった方」
「クラスをしっかりと分けて設計したい方」
「DAO・DTOクラスパターンを使って設計したい方」

2. 今回使用するテーブル

CREATE TABLE item (
id INT NOT NULL	AUTO_INCREMENT,
item_name VARCHAR(20) NOT NULL,
price INT NOT NULL,
item_remarks VARCHAR(50),
PRIMARY KEY(id));

-- 登録順
INSERT INTO item VALUE(0,'りんご',80,null);
INSERT INTO item VALUE(0,'パイナップル',300,'コスタリカ産');
INSERT INTO item VALUE(0,'ドラゴンフルーツ',600,null);

3. 4大命令

SELECT(1つ)

    // idからitemを1つ取得
	public static Optional<ItemDTO> selectItem(int id) {
		String sqlString = "SELECT * FROM item WHERE id = ?;";

		try (Connection con = ConnectionSetting.getDbConnect();
				PreparedStatement ps = con.prepareStatement(sqlString);) {
			ps.setInt(1, id);
			ResultSet rs = ps.executeQuery();

			if (rs.next()) {
				return Optional.of(
						new ItemDTO(rs.getInt("id"), rs.getString("item_name"), rs.getInt("price"),
								rs.getString("item_remarks")));
			} else {
				return Optional.empty();
			}
		} catch (SQLException e) {
			e.printStackTrace();
			return Optional.empty();
		}
	}
  • 引数のidをパラメータ「?」にセットして同じidのitemがitemテーブルにあるかを確認しています。
  • ItemDTOがnullである可能性があるためOptionalにします。
  • このメソッドを呼び出し先では、Optionalの処理をさせましょう。下記に記述例を記載します。
		Optional<ItemDTO> optItem = selectItem(id);
		if (optItem.isPresent()) {
            // itemがnullではないことが判別
			ItemDTO item = optItem.get();
        } else {
			// optItem is null
			System.out.println("検索idのitemは存在しません。");
		}

【演習】引数(id)に1を渡すと、「りんご」のインスタンスが取得できているか確かめましょう

SELECT(複数)

	// 引数の価格よりも安いitemをすべて取得
	public static List<ItemDTO> selectItemList(int price) {
		String sqlString = "SELECT * FROM item WHERE price < ?;";

		try (Connection con = ConnectionSetting.getDbConnect();
				PreparedStatement ps = con.prepareStatement(sqlString);) {
			ps.setInt(1, price);
			ResultSet rs = ps.executeQuery();

			List<ItemDTO> itemList = new ArrayList<>();
			while (rs.next()) {
				itemList.add(new ItemDTO(rs.getInt("id"), rs.getString("item_name"), rs.getInt("price"),
						rs.getString("item_remarks")));
			}
			return itemList;

		} catch (SQLException e) {
			e.printStackTrace();
			return Collections.emptyList();
		}
	}
  • 複数item取得する可能性があるためListに格納します。
  • while文で取得したItemDTOインスタンスを生成してListに追加していきます。
  • このメソッドの呼び出し先で、必要に応じてitemList.isEmpty()を使って処理を分岐させましょう。

【演習】引数(price)に500を渡すと、「りんご」と「パイナップル」のインスタンスが格納されているリストが取得できているか確かめましょう

UPDATE

	// あるItemの値段を変更
	public static Boolean hasUpdatedItem(int price, int id) {
		String sqlString = "UPDATE item SET price = ? WHERE id = ?;";

		try (Connection con = ConnectionSetting.getDbConnect();
				PreparedStatement ps = con.prepareStatement(sqlString);) {
			ps.setInt(1, price);
			ps.setInt(2, id);
			int result = ps.executeUpdate();

			return result == 1;
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
	}
  • 「更新できたかどうか」なので型はBoolean型にします。
  • resultはtureの場合1,falseの場合2になります。

【演習】引数(price = 90,id = 1)を渡して、itemテーブルのりんごのpriceが80へ90に更新しましょう。更新後に正しく更新されているかSELCET文で確かめてみましょう。

INSERT

	// Itemを登録
	public static Boolean hasInsertedItem(String itemName, int price, String remarks) {
		final int id = 0;
		String sqlString = "INSERT INTO item VALUE(?,?,?,?);";

		try (Connection con = ConnectionSetting.getDbConnect();
				PreparedStatement ps = con.prepareStatement(sqlString);) {
			ps.setInt(1, id);
			ps.setString(2, itemName);
			ps.setInt(3, price);
			ps.setString(4, remarks);
			int result = ps.executeUpdate();

			return result == 1;
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
	}
  • 登録する各値を引数から受け取ります。
  • idはAUTO_INCREMENTのためfinal int id = 0にしています。

【演習】4000円のメロン(茨城県産)をitemデータに追加しましょう。

DELETE

	// Itemを削除
	public static Boolean hasDeletedItem(int id) {
		String sqlString = "DELETE FROM item WHERE id = ?;";

		try (Connection con = ConnectionSetting.getDbConnect();
				PreparedStatement ps = con.prepareStatement(sqlString);) {
			ps.setInt(1, id);
			int result = ps.executeUpdate();

			return result == 1;
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
	}
  • DELETEの処理はUPDATEのコードと類似する点が多いです。

【演習】itemテーブルからドラゴンフルーツのデータを削除しましょう。

4. おわりに


ご好評であれば、他にも詰まりそうな点も記事にしていこうと思います。 「いいね & フォロー」いただけますと大変励みになります!
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0