Skip to content
This repository has been archived by the owner on Apr 16, 2024. It is now read-only.

Commit

Permalink
[ch01] Separated the routine of getting DB connection into other class.
Browse files Browse the repository at this point in the history
  • Loading branch information
dhsim86 committed Jun 6, 2017
1 parent 3331777 commit feac2bd
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
17 changes: 17 additions & 0 deletions src/main/java/ch01/springbook/user/dao/SimpleConnectionMaker.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package ch01.springbook.user.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class SimpleConnectionMaker {

public Connection makeNewConnection() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection c = DriverManager.getConnection(
"jdbc:mysql://localhost/tobystudy?useUnicode=true&characterEncoding=UTF-8&useSSL=true&verifyServerCertificate=false",
"study",
"study");
return c;
}
}
10 changes: 8 additions & 2 deletions src/main/java/ch01/springbook/user/dao/UserDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,14 @@

public abstract class UserDao {

private SimpleConnectionMaker simpleConnectionMaker;

public UserDao() {
simpleConnectionMaker = new SimpleConnectionMaker();
}

public void add(User user) throws ClassNotFoundException, SQLException {
Connection c = getConnection();
Connection c = simpleConnectionMaker.makeNewConnection();

PreparedStatement ps = c.prepareStatement(
"INSERT INTO users(id, name, password) VALUES(?, ?, ?)");
Expand All @@ -22,7 +28,7 @@ public void add(User user) throws ClassNotFoundException, SQLException {
}

public User get(String id) throws ClassNotFoundException, SQLException {
Connection c = getConnection();
Connection c = simpleConnectionMaker.makeNewConnection();

PreparedStatement ps = c.prepareStatement(
"SELECT * FROM users WHERE id = ?");
Expand Down

0 comments on commit feac2bd

Please sign in to comment.