JDBC 예제

강정우·2022년 7월 23일
0

JSP, Servlet, JDBC

목록 보기
16/19
post-thumbnail

사원관리 프로그램을 만들어보자

package Exam01;

import java.net.ConnectException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		// 1.등록 2.조회 3.수정 4.삭제 5.종료
		Scanner sc = new Scanner(System.in);
        
        // 프로그램 시작
		while (true) {
			System.out.println("1.등록 2.조회 3.수정 4.삭제 5.종료 >> ");
			int choice = sc.nextInt();
            
            // 등록
			if (choice == 1) {
				System.out.println("===== 등록 =====");
				System.out.print("ID : ");
				String id = sc.next();
				System.out.print("PW : ");
				String pw = sc.next();
				System.out.print("NAME : ");
				String name = sc.next();
				System.out.print("NICK : ");
				String nick = sc.next();

				//객체 선언
				PreparedStatement psmt = null;
				Connection conn = null;

				try {
                	// 컴파일러가 모름 => 따라서 경로지정.
					Class.forName("oracle.jdbc.driver.OracleDriver");
					
					String db_url = "jdbc:oracle:thin:@localhost:1521:xe";
					String db_id = "hr";
					String db_pw = "hr";
                    
                    // 커넥션 열결(생성자)
					conn = DriverManager.getConnection(db_url, db_id, db_pw);

					// 객체가 성공적으로 생성되었을 때
					if (conn != null) {
						System.out.println("DB연결 성공");
					} else {
						System.out.println("DB연결 실패");
					}
                    
					String sql = "INSERT INTO SPRINGMEMBER VALUES(?,?,?,?)";
					psmt = conn.prepareStatement(sql);

					psmt.setString(1, id);
					psmt.setString(2, pw);
					psmt.setString(3, name);
					psmt.setString(4, nick);

					int cnt = psmt.executeUpdate();
					if (cnt > 0) {
						System.out.println("등록성공");
					} else {
						System.out.println("등록실패");
					}
					
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				} catch (SQLException e) {
					e.printStackTrace();
				} finally {
					try {
						// nullpointexception 이 아닐때 진행하겠다.
						if (psmt != null) {
							psmt.close();
						}
						if (conn != null) {
							conn.close();
						}
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			} else if (choice == 5) {
				System.out.println("시스템을 종료합니다.");
				break;
			} else {
				System.out.println("잘못된 명령어입니다.");
			}
		}
		sc.close();
	}
}
profile
智(지)! 德(덕)! 體(체)!

0개의 댓글