IT/부스트코스

부스트 코스 DB연결 웹앱#8 JDBC-1

은세고화 2020. 2. 3. 13:53
반응형

학습 목표

  1. JDBC가 무엇인지 이해한다.

JDBC란 자바를 이용해서 데이터베이스를 조작할 수 있게 하는 것이다.

CMD에서 데이터베이스를 조작하기에는 불편하니 자바를 통해서 조작할 수 있게 만든 것이다.

 

JDBC를 이용한 프로그래밍 방법

  1. import java.sql.*;
  2. 드라이버를 로드한다.
  3. CONNECTION 객체를 생성한다.(DB접속)
  4. STATEMENT 객체를 생성 및 질의 수행(쿼리문 작성)
  5. SQL문에 결과물이 있다면 RESULTSET 객체를 생성한다.(SELECT문처럼 결과문이 있는 경우 사용)
  6. 모든 객체를 닫는다.

JDBC 사용 - 단계별 설명

1.임포트

import java.sql.*;

 

2.드라이버 로드

Class.forName( "com.mysql.jdbc.Driver" );

 

3.Connection 얻기 >> db에 연결함

String dburl = "jdbc:mysql://localhost/dbName";

Connection con = DriverManager.getConnection ( dburl, ID, PWD );

---여기까지의 예제-----

public static Connection getConnection() throws Exception{
	String url = "jdbc:oracle:thin:@117.16.46.111:1521:xe"; 
	String user = "smu";
	String password = "smu";
	Connection conn = null;	//커넥션 객체 생성
	Class.forName("oracle.jdbc.driver.OracleDriver");	//오라클 db사용시 드라이버 얻는법
	conn = DriverManager.getConnection(url, user, password);	//주소를 커넥션에 넣음
	return conn;
}

4.Statement 생성

Statement stmt = con.createStatement();

 

5.질의 수행

ResultSet rs = stmt.executeQuery("select no from user" );

참고
stmt.execute(“query”);             //any SQL
stmt.executeQuery(“query”);     //SELECT
stmt.executeUpdate(“query”);   //INSERT, UPDATE, DELETE

6.ResultSet으로 결과 받기(select문처럼 결과가 있는 경우)

ResultSet rs =  stmt.executeQuery( "select no from user" );
while ( rs.next() )
      System.out.println( rs.getInt( "no") );

데이터를 한번에 받으면 서버에 과부화가 걸리기 때문에 next()를 통해 일정부분 받고 다음으로 넘어가는 식으로 받는다.

 

7. close

rs.close();

stmt.close();

con.close();

 

결국 순서는

코드로 보자면

conn = DBUtil.getConnection();
String sql = "select * from guestbook";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();

conn이 conndection

ps가 쿼리문이 담긴 statement

rs가 결과를 보이기 위한 resultset이다.

반응형