본문 바로가기

[2016 - 2019] 학부 정리/Java

[오늘필기01] jdbc - 18.01.15

16일 평가 : 자바에서만 나옴

[오늘 배울 내용 : jdbc, 파이썬, R설치까지]

----------------------------------------------------------------------------------------------------------------------

[복습]

1. api패키지 확인 -> Token, BoxedPrimitive, Arraylist, Set, Map 확인

2. 클래스 특징 중요 -> 내일 시험

 -추상클래스는 추상메소드가 있어도되고 없어도 된다.

 -추상메소드는 무조던 추상클래스여야 한다.

 -인터페이스는 다중상속이 가능하다.

3. jdbc연결 

 -DAO : Data Access Object, (데이터베이스만 따로 뽑아내는 부분)

[프로젝트 오른쪽 마우스, properties, javaBuildPath, library, external add , oracle6.jar, codec commons1.11.jar]

 -드라이버 확인


 -다이내믹 쿼리 별로 안좋음, 파라미터쿼리가 훨씬 쉽게 하고, 보안 높 

 -LRU알고리즘, 내부 큐, 라이브러리 캐시 

-> 많이사용하는 명령쿼리는 그대로 두거나 캐시에 두는게 좋은데, 다이내믹 쿼리로 하면 재사용이 불가능해서 다른 쿼리로 처리되고 성능이 떨어지게 된다.

----------------------------------------------------------------------------------------------------------------------

[오늘]

jdbc원리 코드를 되도록이면 외워두는게 좋을 듯

try catch 안에 있는 Class.forName()~ 여기 블록

백견이 불여일타p420 - JSPServelet,-jdbc

BOF, EOF row가 위, 아래에 한줄씩 들어감


ex. select 해서 다 가져오기

package jdbc;


import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;


public class SelectMember {

public static void main(String[] args) {

Connection conn = null;

PreparedStatement stmt = null;

ResultSet rs = null;


String sql = 

"select no, user_name, user_id from member " +

"order by no desc "; //오른쪽 끝 공백 주기, 여러줄 나올 것

try {

Class.forName("oracle.jdbc.OracleDriver");

conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","n1","n1");

stmt = conn.prepareStatement(sql);

rs =stmt.executeQuery(); //받아온 결과

System.out.println("번호\t아이디\t이름");

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

while(rs.next()) { //다음 레코드가 존재하면 true

System.out.print(rs.getInt("no")+"\t");

System.out.print(rs.getString("user_id")+"\t");

System.out.print(rs.getString("user_name")+"\n");

}//EoF만나면 false되어 빠져나온다.

} catch (Exception e) {

e.printStackTrace();

}finally {

if(rs != null) try {rs.close();} catch(Exception e) {}

if(stmt != null) try {stmt.close();} catch(Exception e) {}

if(conn != null) try {conn.close();} catch(Exception e) {}

}


}


ex. update문

package jdbc;


import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.util.Scanner;


import org.apache.commons.codec.digest.DigestUtils;


public class UpdateTest {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

String user_id = "";

String user_pw = "";

String user_name = "";

int no = -999;//기왕이면 안들어올것 같은 값으로 초기값 하기


System.out.print("아이디 : ");

user_id = sc.nextLine(); //'--이런식으로 아이디에 적으면 아이디만 맞으면 들어가게 되니까!!

System.out.print("비밀번호 : ");

user_pw = DigestUtils.sha512Hex(sc.nextLine());


Connection conn = null;

PreparedStatement stmt = null;

ResultSet rs = null;


String sql = 

"select no, user_name from member " +

"where user_id=? and user_pw=?";

try {

Class.forName("oracle.jdbc.OracleDriver");

conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","n1","n1");

stmt = conn.prepareStatement(sql);

stmt.setString(1, user_id);

stmt.setString(2, user_pw);

rs =stmt.executeQuery();

if(rs.next()) { //다음 레코드가 존재하면 true

String name = rs.getString("user_name");

no = rs.getInt("no");

System.out.println(name+"(" +user_id+")회원 님이 로그인 하였습니다.");

}else {

System.out.println("아이디 혹은 비밀번호가 틀립니다.");

System.out.println("프로그램이 종료됩니다.");

System.exit(0); //강제로 프로그램 종료

}

/*로그인이 잘 된 상태*/ //if문 뒤에 써도 되지만 더 잘보이게 하기 위해서

System.out.println("회원정보를 수정합니다.");

System.out.print("아이디 : ");

user_id = sc.nextLine(); 

System.out.print("이름 : ");

user_name = sc.nextLine();

StringBuilder sb = new StringBuilder();

sb.append("update member set ");

sb.append("    user_id = ? ");

sb.append("    ,user_name = ? ");

sb.append("where no = ? ");

stmt = conn.prepareStatement(sb.toString()); 

                        //String은 이름만 적어도 됨, builder, buffer는 toString필요 //쿼리가 서버로 날아감


stmt.setString(1, user_id);

stmt.setString(2, user_name);

stmt.setInt(3, no);

//원본데이터에 변경을 가하는 것, 먼저 확인해 줄 필요가 있다. 관리자가 불량인 사람이나 게시판 지워버린 경우

if(stmt.executeUpdate() == 1) {

System.out.println(user_id+"님의 정보가 수정되었습니다.");

}else {

System.out.println("정보수정 에러입니다.");

}

} catch (Exception e) {

e.printStackTrace();

}finally {

if(rs != null) try {rs.close();} catch(Exception e) {}

if(stmt != null) try {stmt.close();} catch(Exception e) {}

if(conn != null) try {conn.close();} catch(Exception e) {}

}


}

}

웹으로 출력하기(먼저 탐캣받기)

http://tomcat.apache.org/

8.0 8.5

dev파일로 옮기기 여기에 압축풀기

이클립스 : openperspective

tomcat 8.5

next

browse -> dev -> apachetomcat8.5~까지 확인

[웹테스트]

프로젝트 만들기

dynamic web project

webdev만들기

generate web.xml 체크


html5으로 바꿔주기

포트충돌나면

apache 더블클릭 -> 포트변경하기



select 문 만들기 스크립트릿 사용해서


<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="EUC-KR">

<title>웹페이지 만들기</title>

</head>

<body>

<h1>My first page...</h1>

</body>

</html> 

 select.jsp

먼저 oracle6.jar 이거 넣기

저기 lib에다가 복사해서 넣기

----------------------------------------------------------------

system.out.,println -> out.println

표출력 -> html언어로 테이블 만들기

-----------------------------------------------------------------

<%@page import="java.sql.DriverManager"%>

<%@page import="java.sql.ResultSet"%>

<%@page import="java.sql.PreparedStatement"%>

<%@page import="java.sql.Connection"%>

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="EUC-KR">

<title>Insert title here</title>

</head>

<body>

<%

Connection conn = null;

PreparedStatement stmt = null;

ResultSet rs = null;


String sql =

"select no, user_name, user_id from member " +

"order  by  no desc ";

try {

Class.forName("oracle.jdbc.OracleDriver");

conn = DriverManager.getConnection(

"jdbc:oracle:thin:@localhost:1521:xe", "n1", "n1");

stmt = conn.prepareStatement(sql);

rs = stmt.executeQuery();

out.println("<table border=1>");

out.println("<tr>");

out.println("<td>번호</td><td>아이디</td><td>이름</td>");

out.println("</tr>");

while(rs.next()) {

out.print("<tr><td>" + rs.getInt("no") + "</td>");

out.print(    "<td>" + rs.getString("user_id") + "</td>");

out.print(    "<td>" + rs.getString("user_name") + "</td></tr>");

}

out.println("</table>");

} catch (Exception e) {

e.printStackTrace();

} finally {

if (rs != null) try {rs.close();} catch(Exception e) {}

if (stmt != null) try {stmt.close();} catch(Exception e) {}

if (conn != null) try {conn.close();} catch(Exception e) {}

}

%>

</body>

</html>


'[2016 - 2019] 학부 정리 > Java' 카테고리의 다른 글

[필기] 18.01.17  (0) 2018.01.17
[오늘필기02] jdbc - 18.01.15  (0) 2018.01.15
18.01.12 자바 - 필기02 미완성  (0) 2018.01.12
18.01.12 자바 - 필기01 미완성  (0) 2018.01.12
18.01.11 자바 - 필기02 미완성  (0) 2018.01.11