Java
[jdbc]MVC
어텀잉
2023. 10. 19. 11:30
728x90
반응형
SMALL
이번시간에는 MVC 패턴을 이용하여 사용자의 입력값을 받고
DML문을 실행하는 법을 알아보겠습니다.
모델 생성하기
public class cafeModel {
String url="jdbc:oracle:thin:@localhost:1521:xe";
String username ="user";
String password="user1234";
//(매개변수 자리)
public void insertcafe(String name,String address,String phone_number,String operating_hours) {
try {
Connection con = DriverManager.getConnection(url,username,password);
String sql = "insert into cafes (name,address)"
+ "values(?,?,?,?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1,name);
ps.setString(2, address);
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
뷰 생성하기
public class cafeView {
//멤버변수로 카페모델을 추가
public cafeModel model ;
//model 매개변수를 받을 수 있는 생성자를 만들어야함
public cafeView(cafeModel model) {
this.model=model;
}
public void addcafeName() {
Scanner sc = new Scanner(System.in);
System.out.println("카페정보를 입력하세요");
System.out.println("카페 이름 : ");
String name = sc.next();
System.out.println("카페 주소 : ");
String address = sc.next();
//카페모델에서 insertcafe 라는 메서드를 가지고 와야함
model.insertcafe(name, address);
System.out.println("카페가 성공적으로 추가되었습니다.");
}
컨트롤러 생성
public class cafeController {
public cafeModel model;
public cafeView view;
//모델과 뷰를 가지고 올 생성자
public cafeController(cafeModel model, cafeView view) {
this.model=model;
this.view=view;
}
}
메인 클래스 생성하기
public class Main {
public static void main(String[] args) {
cafeModel model = new cafeModel();
cafeView view = new cafeView(model);
cafeController controller = new cafeController(model,view);
//view 에서 생성한 addcafeName() 호출
view.addcafeName();
}
}
728x90
반응형
LIST