Java Web Programming 3 CREATE Syntax TABLE create
Java Web Programming 3일차
테이블 생성 쿼리: CREATE Syntax TABLE. . . create table TABLENAME ( FIELD_NAME 1 FIELD_TYPE 1(LEN 1), FIELD_NAME 2 FIELD_TYPE 2(LEN 2), . . . , FIELD_NAMEn FIELD_TYPEn(LENn) ) TABLENAME - 테이블을 식별할 때 사용할 이름 FIELD_NAME - 각 필드의 이름 FIELD_TYPE - 각 필드에 저장될 값의 타입 LEN - 저장될 값의 최대 길이 Example create table MEMBER ( MEMBERID VARCHAR(10) NOT NULL PRIMARY KEY, PASSWORD VARCHAR(10) NOT NULL, NAME VARCHAR(20) NOT NULL, EMAIL VARCHAR(80) ) JSP 2. 0 Programming 10
데이터 삽입 쿼리: INSERT INTO Syntax. . . VALUES. . . insert into TABLENAME (FIELD 1, FIELD 2, . . , FIELDn) values (VALUE 1, VALUE 2, . . , VALUEn) TABLENAME - 테이블을 식별할 때 사용할 이름 FIELDx - 값을 지정할 필드의 이름 VALUEx - 같은 순서에 위치한 필드의 값 필드 목록을 생략하면 모든 필드에 대해서 값을 삽입한다. Example 필드 지정 insert into MEMBER (MEMBERID, PASSWORD, NAME) values ('madvirus', '1234', '최범균') 필드 지정 안함 insert into MEMBER values ('era 13', '5678', '최범균', 'madvirus@empal. com') JSP 2. 0 Programming 11
데이터 조회 쿼리: SELECT. . . Syntax FROM. . . WHERE. . . select FIELD 1, FIELD 2, . . . , FIELDn from TABLENAME [where 검색조건] [order by 정렬순서] TABLENAME - 테이블을 식별할 때 사용할 이름 FIELDx - 값을 읽어올 필드의 이름 where 절에 조건을 입력하면 조건에 해당하는 레코드의 값만 읽어온다. order by 절에 정렬 순서를 입력하면 지정한 순서대로 레코드를 읽어온다. select * from 과 같이 '*'를 사용하면 레코드의 모든 필드를 읽어온다. Example select select * * * * from from MEMBER MEMBER EMPLOY MEMBER where where order NAME = '최범균' and EMAIL='madvirus@empal. com' EMAIL <> '' EMAIL is NULL EMAIL is not NULL where SALARY >= 1000 and SALARY <= 2000 NAME like '최%' by NAME asc, MEMBERID desc JSP 2. 0 Programming 12
데이터 조회 쿼리: 집합 • • sum() : 특정 필드의 합 max() : 특정 필드 중 최대 값 min() : 특정 필드 중 최소값 count() : 검색된 레코드의 개수 Example select count(*) from MEMBER where NAME like '최%' select max(SALARY), min(SALARY) from EMPLOY JSP 2. 0 Programming 13
데이터 수정 쿼리: UPDATE. . . Syntax SET. . . update TABLENAME set FIELD 1=VALUE 1, FIELD 2=VALUE 2, . . . [where 조건절] TABLENAME - 테이블을 식별할 때 사용할 이름 FIELDx - 값을 읽어올 필드의 이름 VALUEx - 변경할 값 where 절이 존재하지 않으면 모든 레코드를 수정한다. where 절이 있는 경우, 조건에 해당하는 레코드만 수정한다. Example update MEMBER set ADDRESS = '서울시' where MEMBERID = 'myid' JSP 2. 0 Programming 14
데이터 삭제 쿼리: DELETE Syntax FROM. . . delete from TABLENAME [where 조건절] TABLENAME - 테이블을 식별할 때 사용할 이름 where 절이 존재하지 않으면 모든 레코드를 삭제한다. where 절이 있는 경우, 조건에 해당하는 레코드만 삭제한다. Example delete from MEMBER where MEMBERID = 'myid' JSP 2. 0 Programming 15
JDBC 프로그래밍의 실행 순서: Example 예제 (1) <%@ page content. Type = "text/html; charset=euc-kr" %> <%@ <%@ <%@ page page import import = = = "java. sql. Driver. Manager" %> "java. sql. Connection" %> "java. sql. Statement" %> "java. sql. Result. Set" %> "java. sql. SQLException" %> 데이터베이스 처리에 필요한 클래스 import <html> <head><title>회원 목록</title></head> <body> MEMBMER 테이블의 내용 <table width="100%" border="1"> <tr> <td>이름</td><td>아이디</td><td>이메일</td> </tr> <% // 1. JDBC 드라이버 로딩 Class. for. Name("com. mysql. jdbc. Driver"); JDBC 드라이버 로딩 Connection conn = null; Statement stmt = null; Result. Set rs = null; JSP 2. 0 Programming 20
JDBC 프로그래밍의 실행 순서: Example 예제 (2) try { String jdbc. Driver = "jdbc: mysql: //localhost: 3306/chap 11? " + "use. Unicode=true&character. Encoding=euc-kr"; String db. User = "jspexam"; String db. Pass = "jspex"; String query = "select * from MEMBER order by MEMBERID"; 데이터베이스 커넥션 생성 // 2. 데이터베이스 커넥션 생성 conn = Driver. Manager. get. Connection(jdbc. Driver, db. User, db. Pass); // 3. Statement 생성 stmt = conn. create. Statement(); 쿼리 실행을 위한 Statement 생성 // 4. 쿼리 실행 rs = stmt. execute. Query(query); 쿼리를 실행해서 결과를 Result. Set에 저장 // 5. 쿼리 실행 결과 출력 while(rs. next()) { %> <tr> Result. Set으로부터 쿼리 결과 읽어옴 <td><%= rs. get. String("NAME") %></td> <td><%= rs. get. String("MEMBERID") %></td> <td><%= rs. get. String("EMAIL") %></td> </tr> <% } JSP 2. 0 Programming 21
JDBC 프로그래밍의 실행 순서: Example 예제 (3) } catch(SQLException ex) { // 에러 발생 } finally { // 6. 사용한 Statement 종료 if (rs != null) try { rs. close(); } catch(SQLException ex) {} if (stmt != null) try { stmt. close(); } catch(SQLException ex) {} // 7. 커넥션 종료 if (conn != null) try { conn. close(); } catch(SQLException ex) {} Statement와 Result. Set 닫음 DB 커넥션 닫음 } %> </table> </body> </html> JSP 2. 0 Programming 22
Code JDBC 드라이버 로딩 try { Class. for. Name("JDBC드라이버 클래스의 완전한 이름"); } catch(Class. Not. Found. Exception ex) { // 지정한 클래스가 존재하지 않을 경우 에러가 발생한다. // 에러 처리 } JDBC 드라이버 클래스 예 • �My. SQL - com. mysql. jdbc. Driver • �오라클 - oracle. jdbc. driver. Oracle. Driver JSP 2. 0 Programming 23
Syntax JDBC URL jdbc: [DBMS]: [데이터베이스식별자] Example My. SQL jdbc: mysql: //localhost: 3306/chap 11? use. Unicode=true&character. Encoding=euc-kr 오라클 jdbc: oracle: thin: @172. 0. 0. 1: 1521: ORCL JSP 2. 0 Programming 24
Code 데이터베이스 커넥션 얻기 Driver. Manager. get. Connection(String jdbc. URL) Driver. Manager. get. Connection(String jdbc. URL, String user, String password) → DB와 연결된 Connection 객체를 리턴한다. • jdbc. URL - 데이터베이스를 나타내는 JDBC URL • user - 데이터베이스 계정 • password - 데이터베이스 계정 암호 Exception Code Connection conn = null; try { conn = Driver. Manager. get. Connection(. . . ); . . . } catch(SQLException ex) {. . . // 예외 처리 } 커넥션을 구하지 못하면 SQLException 예외를 발생 JSP 2. 0 Programming 25
데이터베이스 커넥션 얻기: 예제 Example 코드 Connection conn = null; try { String jdbc. Driver = "jdbc: mysql: //localhost: 3306/chap 11? " + "use. Unicode=true&character. Encoding=euc-kr"; String db. User = "jspexam"; String db. Pass = "jspex"; conn = Driver. Manager. get. Connection(jdbc. Driver, db. User, db. Pass); . . . } catch(SQLException ex) { // 에러 발생 } finally { if (conn != null) try { conn. close(); } catch(SQLException ex) {} } JSP 2. 0 Programming 26
Statement를 사용한 쿼리 실행 Code Statement stmt = null; stmt = conn. create. Statement(); stmt. execute. Query("select 쿼리. . . "); stmt. execute. Update("insert, update, delete 쿼리. . . "); • Result. Set execute. Query(String query) - SELECT 쿼리를 실행한다. SELECT 쿼리를 실행한 결과는 Result. Set에 저장된다. • int execute. Update(String query) - INSERT, UPDATE, DELETE 쿼리를 실행한다. 결과값은 삽입/변경/삭제 된 레코드의 개수 JSP 2. 0 Programming 27
Result. Set. next() 메소드의 이해 Result. Set. next() 메소드와 커서의 이동 rs. next() : true ► 1행 2행 2행 3행 3행 ► rs. next() : true rs. next() : false 1행 1행 1행 2행 2행 2행 3행 3행 3행 ► ► JSP 2. 0 Programming 29
Prepared. Statement를 사용한 쿼 리 실행 1. Connection. prepare. Statement() 메소드를 사용하여 Prepared. Statement 생성 2. Prepared. Statement의 set 메소드를 사용 하여 필요한 값 지정 3. Prepared. Statement의 execute. Query() 또 는 execute. Update() 메소드를 사용하여 쿼 리를 실행. 4. finally 블럭에서 사용한 Prepared. Statement를 닫는다. (close() 메 소드 실행) JSP 2. 0 Programming 30
Prepared. Statement를 사용한 쿼 Code 리 실행 물음표(? )를 사용해서 지정할 값의 위치 명시 Prepared. Statement pstmt = null; pstmt = conn. prepare. Statement( "insert into MEMBER (MEMBERID, NAME, EMAIL) values (? , ? )"); pstmt. set. String(1, mem. ID); 물음표 위치에 들어갈 값을 지정한다. pstmt. set. String(2, name); 물음표의 인덱스 값은 1부터 시작 pstmt. set. String(3, "no-mail@madvirus. net"); pstmt. execute. Update(); • Result. Set execute. Query() - SELECT 쿼리를 실행한다. SELECT 쿼리를 실행한 결과는 Result. Set에 저장된다. • int execute. Update() - INSERT, UPDATE, DELETE 쿼리를 실행한다. 결과값은 삽입/변경/삭제 된 레코드의 개수 JSP 2. 0 Programming 31
Prepared. Statement를 사용하는 이유 1, 반복해서 실행되는 동일 쿼리의 속도를 증가시키기 위해 Code String ids = {"abc", "def", "ghi", . . }; stmt = conn. create. Statement(); stmt. execute. Query("select * form MEMBER where MEMBERID = '"+ids[0]+"'"); stmt. execute. Query("select * form MEMBER where MEMBERID = '"+ids[1]+"'"); stmt. execute. Query("select * form MEMBER where MEMBERID = '"+ids[2]+"'"); ‥‥‥ 매번 쿼리 분석 쿼리분석 시간 단축 한번만 쿼리 분석 String ids = {"abc", "def", "ghi" }; pstmt = conn. prepare. Statement("select * from MEMBER where MEMBERID = ? "); for (int i = 0 ; i < ids. length ; i++) { pstmt. set. String(1, ids[i]); pstmt. execute. Query(); } JSP 2. 0 Programming 32
Prepared. Statement를 사용하는 이유 2, 쿼리에 들어갈 값을 자동으로 변환. 3, 쿼리 코드의 복잡성 없앰. Code String value = "최범'균"; stmt. execute. Query("select * from member where "+ "name = '"+ value. replace. All("'", "''") + "' "); 쿼리에 포함되는 값은 작은따옴표(')를 포함해서 특수 문자의 처리가 필요. 이에 따라 쿼리 코드가 복잡해짐 String value = "최범'균"; pstmt = conn. prepare. Statement("select * from member where name = ? "); pstmt. set. String(1, value); pstmt. execute. Query(); 값에 포함된 특수문자를 Prepared. Statement가 알아서 처리 이에 따라 코드도 간결해짐 JSP 2. 0 Programming 33
- Slides: 35