前回の質問の続きのようですので、こちらに記載します。
質問内容と趣旨があっているかわかりませんが、以下は一例です。データベースはH2Databaseですが。
以下のテーブルがあるとします。
CREATE TABLE SAMPLE_USER (
ID CHAR(10) not null primary key,
NAME VARCHAR(255) not null,
GENDER CHAR(1),
PERIOD CHAR(1)
);
INSERT INTO SAMPLE_USER (ID, NAME, GENDER, PERIOD) VALUES('A000000001', 'サンプル名前01', '1', '1');
INSERT INTO SAMPLE_USER (ID, NAME, GENDER, PERIOD) VALUES('A000000002', 'サンプル名前02', '2', '2');
INSERT INTO SAMPLE_USER (ID, NAME, GENDER, PERIOD) VALUES('A000000003', 'サンプル名前03', '1', '3');
INSERT INTO SAMPLE_USER (ID, NAME, GENDER, PERIOD) VALUES('A000000004', 'サンプル名前04', '2', '4');
プログラムの方は以下のようにSQLを作っているようになると思います。
lang
1 public static void main(String[] args) {
2
3 // フレーム表示
4 JFrame frame = new JFrame("test");
5 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
6 frame.setSize(200, 200);
7 frame.getContentPane().setLayout(null);
8 frame.setLayout(new FlowLayout());
9
10 // パネル
11 JPanel panel = new JPanel();
12 frame.add(panel);
13
14 // チェックボックス
15 JCheckBox[] checkBoxs = new JCheckBox[2];
16 checkBoxs[0] = new JCheckBox("男性");
17 checkBoxs[0].setBounds(306, 12, 98, 23);
18 panel.add(checkBoxs[0]);
19
20 checkBoxs[1] = new JCheckBox("女性");
21 checkBoxs[1].setBounds(306, 40, 98, 23);
22 panel.add(checkBoxs[1]);
23
24 // ボタン
25 JButton button = new JButton("SQL発行");
26 panel.add(button);
27
28 // アクション
29 button.addActionListener(event -> {
30
31 StringBuilder sql = new StringBuilder("SELECT * FROM SAMPLE_USER");
32
33 try (Connection connection = DriverManager.getConnection("jdbc:h2:~/test", "sa", "")) {
34
35 if (checkBoxs[0].isSelected() && checkBoxs[1].isSelected()) {
36 sql.append(" WHERE GENDER IN ('1', '2')");
37 } else if (checkBoxs[0].isSelected()) {
38 sql.append(" WHERE GENDER = '1'");
39 } else if (checkBoxs[1].isSelected()) {
40 sql.append(" WHERE GENDER = '2'");
41 }
42
43 try (PreparedStatement ps = connection.prepareStatement(sql.toString())) {
44
45 try (ResultSet rs = ps.executeQuery()) {
46 System.out.println("-結果-");
47 while (rs.next()) {
48 System.out.println(rs.getString(1));
49 }
50 System.out.println("----");
51 }
52
53 } catch (Exception e) {
54 e.printStackTrace();
55 }
56
57
58 } catch (Exception e) {
59 e.printStackTrace();
60 }
61
62 });
63
64 // 表示
65 frame.setVisible(true);
66
67 }