티스토리 뷰

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.







공지사항
최근에 올라온 글
최근에 달린 댓글
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
글 보관함