Statement를 사용하지 말고 PreparedStatement를 사용하라고 권장 하더라..


아래는 예제


public void add(User user) throws ClassNotFoundException, SQLException{

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

Connection c = DriverManager.getConnection("jdbc:mysql://localhost/test", "sa", "pw!");

PreparedStatement ps = c.prepareStatement("insert into users(id, name, password) values(?,?,?)");

ps.setString(1, user.getId());

ps.setString(2, user.getName());

ps.setString(3, user.getPassword());

ps.executeUpdate();

ps.close();

c.close();

}

public User get(String id) throws ClassNotFoundException, SQLException{

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

Connection c = DriverManager.getConnection("jdbc:mysql://localhost/test", "sa", "pw!");

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

ps.setString(1, id);

ResultSet rs = ps.executeQuery();

rs.next();

User user = new User();

user.setId(rs.getString("id"));

user.setId(rs.getString("name"));

user.setId(rs.getString("password"));

rs.close();

ps.close();

c.close();

return user;

}

+ Recent posts