[JAVA] JDBC 프로그래밍 기초

merci·2023년 1월 6일
1

JAVA

목록 보기
4/10

자바에서는 JDBC API 를 이용해서 데이터베이스 프로그래밍을 한다.
간단한 사용법을 알아보자.

SQL

  • SQL은 관계형 데이터베이스 관리 시스템에서 사용한다.
  • 스키마 생성,데이터 검색, 관리, 수정, 데이터베이스 객체 접근을 할 수 있다.


JDBC

  • 관계형 데이터베이스에 저장된 데이터를 접근, 조작할 수 있게 하는 API
  • 다양한 DBMS를 종류에 상관없이 JDBC API로 다룰수 있다.
  • DBMS에 맞는 JDBC 드라이버만 있으면 된다.
  • JDBC의 구조




JDBC 를 다루기 앞서 사용할 테이블을 생성해보자

create table student2
	(id	char(7)
	,name varchar(10)
	,dept varchar(20));

insert into student2 values('1091011','김철수','컴퓨터시스템');
insert into student2 values('0792012','최고봉','멀티미디어');
insert into student2 values('0494013','이기자','프로그래머');

JDBC를 이용하기 전에 라이브러리에 해당 DBMS에 맞는 드라이버를 넣어야 한다.
이클립스의 경우 Build Path를 이용해서 jar파일을 추가한다.

JDBC 를 이용해서 DB를 조회하는 코드는 다음과 같다

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Jdbc2 {
	public static void main(String[] args) {
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs;
		try {	
			Class.forName("com.mysql.cj.jdbc.Driver"); // 해당 드라이버를 클래스로더에 넘겨준다.
            // 동적으로 자바 클래스를 로딩한다. 드라이버 인스턴스를 생성하여 DriverManager에 등록
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/green","root","1234");
			System.out.println("DB 연결 완료");
			stmt = conn.createStatement();  // Statement 객체 생성  (SQL문을 사용하게 해준다)
            
			rs = stmt.executeQuery("select * from student2");   
			printData(rs); 				// 첫번째 결과
            
		} catch (ClassNotFoundException e) {
			//	e.printStackTrace();
			System.out.println("JDBC 드라이버 로드 에러");
		}catch (SQLException e) {  // 처음에 빨간줄 떳는데 DriverManager 적으니까 사라짐 맞나 ?
			System.out.println("DB 연결 오류");
		} finally {
			if (stmt !=null) try { stmt.close(); } catch(SQLException e) {}
			if (conn !=null) try { conn.close(); } catch(SQLException e) {}
			// 존재 하지 않는 객체를 닫을수 없으므로 null 인지 먼저 확인
		}
	}
	
	private static void printData(ResultSet rs) throws SQLException {
		while(rs.next()) {
			System.out.print(rs.getString("id")+"  |  ");
			System.out.print(rs.getString("name")+"  |  ");
			System.out.println(rs.getString("dept"));
		}
		rs.close();
	}
}
// 첫번째 결과
DB 연결 완료
1091011  |  김철수  |  컴퓨터시스템
0792012  |  최고봉  |  멀티미디어
0494013  |  이기자  |  프로그래머

getConnection() 메소드는 DB 와 연결된 Connection 객체를 리턴한다.
ResultSet 클래스 는 현재 데이터의 행(레코드 위치)을 가리키는 커서(cursor)를 관리한다
커서의 초기 값은 첫 번째 행 이전을 가리킴
next() 메소드를 이용해서 커서가 이동한다.

위처럼 메소드를 이용해서 출력하면 재사용하기 좋아진다.

데이터 조회는 excuteQuery() 메소드를 이용하고,
데이서 수정은 excuteUpdate() 메소드를 이용한다.




데이터를 추가,변경,삭제 해보자

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Jdbc3 {
	public static void main(String[] args) {
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs;
		try {	
			Class.forName("com.mysql.cj.jdbc.Driver"); 
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/green","root","1234");
			System.out.println("DB 연결 완료");
			stmt = conn.createStatement();
            
            // 아래의 두줄씩의 코드를 한번씩 사용한다고 하면
			stmt.executeUpdate("insert into student2 values('3262334','우상혁','높이뛰기')");  
			printData(stmt);    // 첫번째 결과
			
			stmt.executeUpdate("update student2 set id='5913423' where name='우상혁'");
			printData(stmt);	// 두번째 결과
			
			stmt.executeUpdate("delete from student2 where name='우상혁'");
			printData(stmt);	// 세번째 결과
			
		} catch (ClassNotFoundException e) {
			System.out.println("JDBC 드라이버 로드 에러");
		}catch (SQLException e) {  
			System.out.println("DB 연결 오류");
		}finally {
    	if (stmt !=null) try { stmt.close(); } catch(SQLException e) {}
		if (conn !=null) try { conn.close(); } catch(SQLException e) {}
		}
	}
	private static void printData(Statement stmt) throws SQLException {
		ResultSet rs = stmt.executeQuery("select * from student2");
		while(rs.next()) {
			System.out.print(rs.getString("id")+"  |  ");
			System.out.print(rs.getString("name")+"  |  ");
			System.out.println(rs.getString("dept"));
		}
		rs.close();
	}
}
//첫번째 결과
DB 연결 완료
1091011  |  김철수  |  컴퓨터시스템
0792012  |  최고봉  |  멀티미디어
0494013  |  이기자  |  프로그래머
3262334  |  우상혁  |  높이뛰기 // 우상혁 추가


//두번째 결과
DB 연결 완료
1091011  |  김철수  |  컴퓨터시스템
0792012  |  최고봉  |  멀티미디어
0494013  |  이기자  |  프로그래머
5913423  |  우상혁  |  높이뛰기  // 우상혁의 id가 변경되었다.


//세번째 결과
DB 연결 완료
1091011  |  김철수  |  컴퓨터시스템
0792012  |  최고봉  |  멀티미디어
0494013  |  이기자  |  프로그래머 // 우상혁 삭제
profile
작은것부터

0개의 댓글