質問編集履歴

1

Main メソッド内\(DbConnectionクラスを呼び出す側\)で ResultSet Statement Connection を close する用修正しました。

2017/01/20 14:29

投稿

syabon
syabon

スコア11

test CHANGED
File without changes
test CHANGED
@@ -34,7 +34,7 @@
34
34
 
35
35
 
36
36
 
37
- ###該当のソースコード
37
+ ###該当のソースコード(質問後に修正しています。)
38
38
 
39
39
  ```Java
40
40
 
@@ -50,6 +50,8 @@
50
50
 
51
51
  private String url = "jdbc:mysql://localhost:3306/database?useSSL=false";
52
52
 
53
+ private String drv = "com.mysql.jdbc.Driver";
54
+
53
55
  private String id = "root";
54
56
 
55
57
  private String pass = "";
@@ -102,10 +104,6 @@
102
104
 
103
105
  return null;
104
106
 
105
- }finally{
106
-
107
- close(); //ここで例外が発生しているよう
108
-
109
107
  }
110
108
 
111
109
  }
@@ -144,66 +142,56 @@
144
142
 
145
143
 
146
144
 
147
- //他のクラスから利用する際、このメソッドを呼び出すことでclose処理を一括で実行したい
148
-
149
145
  public boolean close(){
150
146
 
151
147
  try{
152
148
 
153
- if(result != null){
154
-
155
- result.close();
149
+ stmt.close();
150
+
151
+ con.close();
152
+
153
+ }catch(SQLException ex){
154
+
155
+ ex.printStackTrace();
156
+
157
+ return false;
158
+
159
+ }
160
+
161
+ return true;
162
+
163
+ }
164
+
165
+
166
+
167
+ public static void main(String[] args){
168
+
169
+
170
+
171
+ try {
172
+
173
+ DbConnection con = new DbConnection();
174
+
175
+ Cart cart = new Cart();
176
+
177
+ ResultSet result = con.executeQuery("SELECT * FROM PRODUCTS");
178
+
179
+ while(result.next()){
180
+
181
+ Product p = new Product(result.getInt(1),result.getString(2),result.getString(3),result.getString(4));
182
+
183
+ cart.addItem(p,10);
156
184
 
157
185
  }
158
186
 
159
- if(stmt != null){
160
-
161
- stmt.close();
162
-
163
- }
164
-
165
- if(con != null){
166
-
167
- con.close();
168
-
169
- }
170
-
171
- }catch(SQLException ex){
172
-
173
- ex.printStackTrace();
174
-
175
- return false;
176
-
177
- }
178
-
179
- return true;
180
-
181
- }
182
-
183
-
184
-
185
- public static void main(String[] args){
186
-
187
- try {
188
-
189
- DbConnection con = new DbConnection();
187
+ con.close(); //StatementとConnectionをクローズ
190
-
191
- Cart cart = new Cart();
188
+
192
-
193
- ResultSet result = con.executeQuery("SELECT * FROM PRODUCTS");
194
-
195
- while(result.next()){
196
-
197
- Product p = new Product(result.getInt(1),result.getString(2),result.getString(3),result.getString(4));
198
-
199
- cart.addItem(p,10);
200
-
201
- }
202
-
203
- con.close(); //タを読み出し
189
+ con.result.close(); //ResultSetをクロズ(不要になっ時点閉じる)
204
190
 
205
191
  cart.show();
206
192
 
193
+
194
+
207
195
  } catch (SQLException ex) {
208
196
 
209
197
  Logger.getLogger(DbConnection.class.getName()).log(Level.SEVERE, null, ex);