티스토리 뷰

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.





공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함