質問編集履歴

1

Daoのコードを掲載しました

2020/06/05 02:52

投稿

commit
commit

スコア2

test CHANGED
File without changes
test CHANGED
@@ -20,7 +20,167 @@
20
20
 
21
21
 
22
22
 
23
-
23
+ ```java
24
+
25
+ package work;
26
+
27
+
28
+
29
+ import java.sql.Connection;
30
+
31
+ import java.sql.DriverManager;
32
+
33
+ import java.sql.ResultSet;
34
+
35
+ import java.sql.Statement;
36
+
37
+
38
+
39
+ public class Dao {
40
+
41
+
42
+
43
+ private String driver;
44
+
45
+ private String url;
46
+
47
+ private String user;
48
+
49
+ private String password;
50
+
51
+ private Connection connection;
52
+
53
+ private Statement statement;
54
+
55
+ private ResultSet resultset;
56
+
57
+
58
+
59
+ /**
60
+
61
+ * コンストラクタ
62
+
63
+ * @param driver ドライバー
64
+
65
+ * @param url URL
66
+
67
+ * @param user ユーザー名
68
+
69
+ * @param password パスワード
70
+
71
+ */
72
+
73
+ public Dao(String driver, String url, String user, String password) {
74
+
75
+ this.driver = driver;
76
+
77
+ this.url = url;
78
+
79
+ this.user = user;
80
+
81
+ this.password = password;
82
+
83
+ }
84
+
85
+
86
+
87
+ /**
88
+
89
+ * 引数なしのコンストラクタ
90
+
91
+ * 既定値を使用する
92
+
93
+ */
94
+
95
+ public Dao() {
96
+
97
+ driver = "ドライバー";
98
+
99
+ url = "jdbc:mariadb://localhost:3306/DB名";
100
+
101
+ user = "ユーザ名";
102
+
103
+ password = "パスワード";
104
+
105
+ }
106
+
107
+
108
+
109
+ /**
110
+
111
+ * データベースへの接続を行う
112
+
113
+ */
114
+
115
+ public synchronized void open() throws Exception {
116
+
117
+ Class.forName(driver);
118
+
119
+ connection = DriverManager.getConnection(url, user, password);
120
+
121
+ statement = connection.createStatement();
122
+
123
+ }
124
+
125
+
126
+
127
+ /**
128
+
129
+ * SQL 文を実行した結果の ResultSet を返す
130
+
131
+ * @param sql SQL 文
132
+
133
+ */
134
+
135
+ public ResultSet getResultSet(String sql) throws Exception {
136
+
137
+ if ( statement.execute(sql) ) {
138
+
139
+ return statement.getResultSet();
140
+
141
+ }
142
+
143
+ return null;
144
+
145
+ }
146
+
147
+
148
+
149
+ /**
150
+
151
+ * SQL 文の実行
152
+
153
+ * @param sql SQL 文
154
+
155
+ */
156
+
157
+ public void execute(String sql) throws Exception {
158
+
159
+ statement.execute(sql);
160
+
161
+ }
162
+
163
+
164
+
165
+ /**
166
+
167
+ * データベースへのコネクションのクローズ
168
+
169
+ */
170
+
171
+ public synchronized void close() throws Exception {
172
+
173
+ if ( resultset != null ) resultset.close();
174
+
175
+ if ( statement != null ) statement.close();
176
+
177
+ if ( connection != null ) connection.close();
178
+
179
+ }
180
+
181
+ }
182
+
183
+ ```
24
184
 
25
185
 
26
186