728x90
JDBC 필요성
- JAVA DataBase Connectivity
- 관계형 DB에 저장된 DATA를 접근 및 조작할 수 있게 하는 인터페이스 기반 자바 API
데이터관리 프로그램
작업 원리
연습하기 1
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
public class Ex01insert {
public static void main(String[] args) {
// 프로그램이 시작되면 사용자의 정보를 입력받아 DB에 전달하기
Scanner sc =new Scanner(System.in);
System.out.println("가입 id: ");
String id = sc.next();
System.out.println("가입 pw: ");
String pw = sc.next();
System.out.println("가입 name: ");
String name = sc.next();
System.out.println("가입 age: ");
int age = sc.nextInt();
//1.드라이버로딩 > 동적 로딩
// 증요~!! 해당 프로젝트 내에 ojdbc6.jar 무조건 있어야한다.
// 경로가 오타가 날 수 있으니 try catch 사용
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
//2. 데이터베이스 연결
String db_url = "jdbc:oracle:thin:@localhost:1521:xe";
String db_user = "hr";
String db_pw = "12345";
// connection 객체 : db 접속에 대한 결과를 담을 수 있는 객체
Connection conn = DriverManager.getConnection(db_url, db_user, db_pw);
// 접속여부 판단
if(conn!=null) {
System.out.println("데이터베이스 접속 성공");
}else {
System.out.println("데이터베이스 접속 실패");
}
//3. 쿼리(sql) 작성
// 테이블 생성 > member
// 컬럼 > id(20), pw(20), name(20), age
String sql = "insert into member values(?,?,?,?)";
PreparedStatement psmt = conn.prepareStatement(sql);
// sql 문장에 연결해야 하는 변수 연결!
psmt.setString(1, id); // 0으로 잡지 않을것!!
psmt.setString(2, pw);
psmt.setString(3, name);
psmt.setInt(4, age);
// executeQuery : 실행시 테이블의 전후가 바뀌지 않는 sql 실행 >> select
// executeupdate: 테이블 실행시 테이블의 전후가 바뀌는 sql 실행방법> insert, delete,update
int result = psmt.executeUpdate();
//4. 결과 처리
if (result > 0) {
System.out.println("회원가입 성공");
} else {
System.out.println("회원가입 실패");
}
//5. 자원 반납 > psmt, conn (최근에 사용했던거 부터 반납)
// psmt(2) eodu<< (1) 반납, conn(1) >> (2)
psmt.close();
conn.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
// 수정가ㄴ능e.printStackTrace();
System.out.println("동적 로딩 오류");
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("DB오류");
}
}
}
연습하기 2
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Ex02select {
public static void main(String[] args) {
// 실행하면 member테이블의 전체내용을 보여주는 select기능 만들기
//1. 동적로딩 >> 자바와 DB를 연결하는 연결다리
try {
Class.forName ("oracle.jdbc.driver.OracleDriver");
String db_url = "jdbc:oracle:thin:@localhost:1521:xe";
String db_user = "hr";
String db_pw = "12345";
//2. 데이터베이스 연결
Connection conn = DriverManager.getConnection(db_url, db_user, db_pw);
//3. sql실행
String sql = "select*from member";
PreparedStatement psmt = conn.prepareStatement(sql);
ResultSet rs = psmt.executeQuery();
if(rs !=null) {
System.out.println("성공");
}else {
System.out.println("실패");
}
//4. 결과로 돌아오는 result 출력하기 !!
// 내가 가지고 올수 있는한 확인하기 위해 while문 사용하기
while(rs.next()) {
String id = rs.getString(1);
System.out.println("결과 :"+ id);
String pw = rs.getString(2);
System.out.println("결과 :"+ pw);
String name = rs.getString(3);
System.out.println("결과 :"+ name);
int age = rs.getInt(4);
System.out.println("결과 :"+ age);
}
//5. 자원반납
if(psmt !=null) {
psmt.close();
}
if(conn !=null) {
conn.close();
}
} catch (Exception e) {
System.out.println("오류 발생");
}
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
import javax.lang.model.util.ElementScanner14;
public class Ex02select {
public static void main(String[] args) {
// 실행하면 member테이블의 전체내용을 보여주는 select기능 만들기
// 1. 동적로딩 >> 자바와 DB를 연결하는 연결다리
PreparedStatement psmt = null ;
Connection conn = null ;
//사용자로부터 id와 pw입력받아
// 해당하는 회원의 전체정보 출력
Scanner sc = new Scanner(System.in);
System.out.println("id 입력>>");
String id2 = sc.next();
System.out.println("pw 입력>>");
String pw2 = sc.next();
try {
Class.forName ("oracle.jdbc.driver.OracleDriver");
String db_url = "jdbc:oracle:thin:@localhost:1521:xe";
String db_user = "hr";
String db_pw = "12345";
//2. 데이터베이스 연결
conn = DriverManager.getConnection(db_url, db_user, db_pw);
//3. sql실행
String sql = "select*from member where id =? and pw=?";
psmt = conn.prepareStatement(sql);
psmt.setString(1,id2);
psmt.setString(2,pw2);
ResultSet rs = psmt.executeQuery();
if(rs !=null) {
System.out.println("성공");
}else {
System.out.println("실패");
}
//4. 결과로 돌아오는 result 출력하기 !!
// 내가 가지고 올수 있는한 확인하기 위해 while문 사용하기
while(rs.next()) {
String id = rs.getString(1);
System.out.println("결과 :"+ id);
String pw = rs.getString(2);
System.out.println("결과 :"+ pw);
String name = rs.getString(3);
System.out.println("결과 :"+ name);
int age = rs.getInt(4);
System.out.println("결과 :"+ age);
}
//5. 자원반납
// if(psmt !=null) {
// psmt.close();
// }
// if(conn !=null) {
// conn.close();
// }
//
} catch (Exception e) {
System.out.println("오류 발생");
}
finally {
//무조건 마지막에 한번은 실행 할 수 있는 구조!!
//5. 자원반납
try {
if(psmt !=null) {
psmt.close();
}
if(conn !=null) {
conn.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//finally
} // main
} // class
출처: 스마트인재개발원
728x90
반응형
'DATA 분석 교육 과정 (2024.02~08) > JAVA' 카테고리의 다른 글
JAVA_OOP (0) | 2024.03.26 |
---|---|
JAVA_추상화(추상메소드, 추상클래스) (0) | 2024.03.18 |
JAVA_상속 (0) | 2024.03.18 |
JAVA_Music Playlist 만들기 (0) | 2024.03.18 |
JAVA_Collection, ArrayList (0) | 2024.03.17 |