본문 바로가기

IT

11-1. JSP - JDBC 프로그래밍 select, delete

6. DELETE 쿼리문 을  짜보자. (11에서 만든 member테이블의 바나나id를 삭제해보자)

package kr.co.koo.jdbc.basic;

import java.sql.*;
import java.util.Scanner;

public class JdbcDelete {

	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		
		System.out.println("삭제할 회원의 ID를 입력하세요.");
		System.out.print("> ");
		String id = sc.next();
		
		String url = "jdbc:mysql://localhost:3306/jsp_practice";
		String uid = "jsp"; //root도 가능하다.
		String upw = "jsp"; //mysql
		
		Connection conn = null;
		Statement stmt = null;
		
		String sql = " DELETE FROM member WHERE id='"+ id +"' ";
		
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(url, uid, upw);
			stmt = conn.createStatement();
			int resultNum = stmt.executeUpdate(sql);
			
			if(resultNum == 1) {
				System.out.println("회원ID: " 
			+ id + "이(가) 정상 삭제되었습니다.");
			} else {
				System.out.println("삭제에 실패했습니다.");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				conn.close();
				stmt.close();
				sc.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

}

7.select 쿼리문을 짜보자. 

delete insert, update 은 결과가 성공, 실패로 뜨지만 select는 결과값이 표로 뜨기 때문에 표를 담을수 있는 변수나 객체가 필요하다.

package kr.co.koo.jdbc.basic;

import java.sql.*;

public class JdbcSelect {

	public static void main(String[] args) {

		String url = "jdbc:mysql://localhost:3306/jsp_practice";
		String uid = "jsp";
		String upw = "jsp";

		String sql = "SELECT * FROM member";

		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;  //select문에서만 사용하는 객체.

		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(url, uid, upw);
			stmt = conn.createStatement();

			rs = stmt.executeQuery(sql); // select는 다른 것들과 달리 표를 출력한다. 
			//즉 표를 ResultSet에 담음. executeQuery의 값은 ResultSet으로 리턴.

			/*
			 - Select쿼리문의 실행 결과 데이터가 한 줄이라도 존재한다면
			   rs.next()메서드는 true를 리턴하며, 해당 행을 지목합니다.
			 */

			System.out.println("=========================================");
			while(rs.next()) {  
			/*
			- rs.next()는 커서다. 표에서 각 행을 가르킨다. 그리고 rs.getString로 값을 리턴함.
            - rs.next();는 첫번째 행, rs.next()rs.next()는 두번째 행, 전체행은 while(rs.next())으로..
			*/			

			/*
			 - select의 실행 결과의 컬럼 레코드를 읽어오려면
			   getString(), getInt() 등의 메서드를 사용합니다.
			 - 해당 메서드의 매개값으로 읽어올 테이블의 컬럼명을 지정합니다.
				 */
				String id = rs.getString("id");
				String pw = rs.getString("pw");
				String name = rs.getString("name");
				String email = rs.getString("email");
				System.out.printf("# 아이디: %s, 비번: %s, 이름: %s, 이메일: %s\n"
						, id, pw, name, email);
			}			

			System.out.println("=========================================");


		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				conn.close(); stmt.close(); rs.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}
}