본문으로 바로가기

Toby의 Spring3 따라하기-제3편 connectionMaker interface 이용해서 분리하기





UserDao.java

import java.sql.*;


/**
* Created by krkim on 2015-09-08.
*/
public class UserDao {

ConnectionMaker connectionMaker;

public UserDao(ConnectionMaker connectionMaker) {
this.connectionMaker = connectionMaker;
}


public void add(User user) throws SQLException {

Connection c = null;
try {
c = connectionMaker.getConnection();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

PreparedStatement ps = c.prepareStatement("insert into users(id, password, name) values(?,?,?)");
ps.setString(1, user.getId());
ps.setString(2, user.getPassword());
ps.setString(3, user.getName());

ps.executeUpdate();

ps.close();
c.close();

}

public User get(String id) throws SQLException {

Connection c = null;
try {
c = connectionMaker.getConnection();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

PreparedStatement ps = c.prepareStatement("select * from users where id=?");
ps.setString(1, id);

ResultSet rs = ps.executeQuery();
rs.next();

User user = new User(rs.getString("id"), rs.getString("password"), rs.getString("name") );

rs.close();
ps.close();
c.close();

return user;
}

}



ConnectionMaker.java(interface;인터페이스)

import java.sql.Connection;

import java.sql.SQLException;

/**
* Created by krkim on 2015-09-08.
*/
public interface ConnectionMaker {

public Connection getConnection() throws ClassNotFoundException, SQLException;
}




KConnectionMaker.java(인터페이스 구현체)

import java.sql.Connection;

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

/**
* Created by krkim on 2015-09-08.
*/
public class KConnectionMaker implements ConnectionMaker{

@Override
public Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");

Connection c = DriverManager.getConnection(
"jdbc:mysql://localhost/krkdb",
"root",
"111111"
);


return c;
}
}




end.






댓글을 달아 주세요