본문으로 바로가기

Toby의 Spring3 따라하기-제2편 UserDao.class 만들기






UserDao.java

import java.sql.*;

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

private Connection getConnection() throws ClassNotFoundException, SQLException {

Class.forName("com.mysql.jdbc.Driver");

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


return c;
}

public void add(User user) throws SQLException {
Connection c = null;

try {
c = 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 = 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;
}

}


getConnection()을 분리하는 것까지 했음.



end.








댓글을 달아 주세요