11package com .wildcodeschool .wildandwizard .repository ;
22
3+ import java .sql .Connection ;
4+ import java .sql .Date ;
5+ import java .sql .DriverManager ;
6+ import java .sql .PreparedStatement ;
7+ import java .sql .ResultSet ;
8+ import java .sql .SQLException ;
9+ import java .sql .Statement ;
10+
311import com .wildcodeschool .wildandwizard .entity .Wizard ;
412
5- import java . sql .* ;
13+ import util . JdbcUtils ;
614
715public class WizardRepository {
816
@@ -13,11 +21,14 @@ public class WizardRepository {
1321 public Wizard save (String firstName , String lastName , Date birthday ,
1422 String birthPlace , String biography , boolean muggle ) {
1523
24+ Connection connection = null ;
25+ PreparedStatement statement = null ;
26+ ResultSet generatedKeys = null ;
1627 try {
17- Connection connection = DriverManager .getConnection (
28+ connection = DriverManager .getConnection (
1829 DB_URL , DB_USER , DB_PASSWORD
1930 );
20- PreparedStatement statement = connection .prepareStatement (
31+ statement = connection .prepareStatement (
2132 "INSERT INTO wizard (first_name, last_name, birthday, birth_place, biography, is_muggle) VALUES (?, ?, ?, ?, ?, ?)" ,
2233 Statement .RETURN_GENERATED_KEYS
2334 );
@@ -32,7 +43,7 @@ public Wizard save(String firstName, String lastName, Date birthday,
3243 throw new SQLException ("failed to insert data" );
3344 }
3445
35- ResultSet generatedKeys = statement .getGeneratedKeys ();
46+ generatedKeys = statement .getGeneratedKeys ();
3647
3748 if (generatedKeys .next ()) {
3849 Long id = generatedKeys .getLong (1 );
@@ -43,6 +54,10 @@ public Wizard save(String firstName, String lastName, Date birthday,
4354 }
4455 } catch (SQLException e ) {
4556 e .printStackTrace ();
57+ } finally {
58+ JdbcUtils .closeResultSet (generatedKeys );
59+ JdbcUtils .closeStatement (statement );
60+ JdbcUtils .closeConnection (connection );
4661 }
4762 return null ;
4863 }
0 commit comments