[JSP] JSP + DB 연동 기본 구조(JDBC 로딩/DB 연동/SQL 실행 및 반환데이터 처리)

 1. JDBC 드라이버 로딩하기   

- 드라이버 이름으로 JDBC 드라이버 로딩

- Class.forName("org.gjt.mm.mysql.Driver");

 

import java.sql.*;

public class Test {
	public static void main(String() args) {
	
	try {
		// 드라이버 이름. DB 관련 구문 중 제일 먼저 기술
		Class.forName("org.gjt.mm.mysql.Driver"); 
	} catch (classNotFoundException e) {
		System.err.println("클래스가 없음 : " + e.getMessage());
	}       
}

 

 

 

   2. DB에 연결하기   

- java.sql.Connection클래스와 java.sql.DriverManager 클래스를 이용하여 DB 연동

- Connection db = DriverManager.getConnection(url, "id", "pw");

- 연결된 DB정보는 Connection 객체인 db에 보관

 

// java.sql.Connection 클래스와 java.sql.DriverManager 클래스 사용
// java.sql.DriverManager의 getConnection()가 DB에 연결
// 연결된 DB 정보를 Connection 클래스의 객체인 db가 보관

try {
	String url = "jdbc:mysql://localhost/goods";
	Connection db = DriverManager.getConnection(url, "id", "pw");
} catch (SQLException e) {
	System.err.println("SQL 에러 : " + e.getMessage());
}

 

 

 

 

 

   3. SQL 사용하기   

3-1) Statement 클래스

- (1) Connection 클래스의 createStatement() 함수를 호출하여 Statement 클래스의 객체를 생성

- (2) Statment 클래스의 executeQuery() 함수로 SQL 명령어 실행

 

// connection 클래스의 createStatemeont() 메소드로 Statement 클래스의 객체 stmt를 만듦
// 그 stmt 객체의 executeQuery() 함수를 호출하여 SQL 명령어 실행
// *connection 클래스는 SQL명령어를 실행시키는 기능이 있는 Statement 클래스의 객체를(stmt)를 만드는 역할만하며, 
// *SQL명령어의 실행 자체는 Statement 클래스의 객체인 stmt 이용

try {
	String url = "jdbc:mysql://localhost/databaseName";
	Connection db = DriverManager.getConnection(url, "id", "pw");

	// (1) SQL실행을 위한 stmt 객체 생성					
	Statement stmt = db.createStatement();		
	// (2) SQL 실행
	ResultSet rs = stmt.executeQuery("select * from tablename");	

...

} catch (SQLException e) {
	System.err.println("SQL 에러 : " + e.getMessage());
}

 

3-2) PreparedStatement 클래스

- (1) 명령어를 정의, (2) 인수 전달받고, (3) 명령어를 실행

- (1) 명령어 정의시 ?를 사용하여 (2) 전달받은 인수를 적용하여 변경가능

 

// 명령어를 정의하고, 인수를 전달받고, 명령어를 실행하는데 사용
// 명령어 포맷을 준비해두고 SELET문의 ? 부분이 인수 역할을 하여 변경하여 사용
// ? 값만 계속 바꿔주면 Variable를 기준으로 여러 데이터를 검색할 수 있게 됨
// 일종의 명령어 틀이라고 보면됨
// executeQuery() 메소드에 의해 실행됨

try {
	String url = "jdbc:mysql://localhost/DBName";
	Connection db = DriverManager.getConnection(url, "id", "pw");

	// (1) SQL문 실행을 위한 stmt 객체 생성. 
	PreparedStatement stmt = db.prepareStatement("select * from tableName where variable = ?");
	
	// (2) select문의 인자 변경
	stmt.setString(1, "3");
    
	// (3) SQL문 실행
	Resultset rs = stmt.executeQuery();

	....
	
    stmt.setString(1,"1");
	rs = stmt.executeQuery();

	...

} catch (SQLException e) {
	System.err.println("SQL 에러 : " + e.getMessage());
}

 

 

3-3) ResultSet 클래스 

- SQL문이 실행되어 결과로 반환한 데이터들을 관리하는 클래스

- ResultSet 클래스는 다음, 이전, 처음, 마지막 레코드로 이동하는 메소드 제공하며 이를 통해 반환된 레코드들 사이를 이동하면서 데이터를 읽어옴

- getXXX 함수를 이용하여 레코드 내의 각 필드들을 데이터타입에 맞게 읽어올 수 있음

// 쿼리문이 실행되어 결과로 반환된 데이터들을 관리하는 클래스
// ResultSet 클래스는 다음, 이전, 처음, 마지막 레코드로 이동하는 메소드를 제공하며 반환된 레코드 사이를 이동하면서 읽을 수 있음
// 또한 getXXX 메소드를 이용하여, 레코드 내의 각 필드들을 데이터 타입에 맞게 읽을 수 있음

String url = "jdbc:mysql://localhost/goods";
Connection db = DriverManager.getConnection(url, "id", "pw");

Statement stmt = db.createStatement();
ResultSet rs = stmt.executeQuery("select * from tablename");

// ResultSet 클래스의 next() 함수를 이용하여 다음 레코드로 이동
while(rs.next()) {

	// get함수를 호출하여 레코드 내 필드들을 읽어옴
	String no = rs.getInt("variable");
	String name = rs.getChar("name");
	String price = rs.getInt("price");
    
	System.out.println(variable + ":" + name + ":" + price);
}

 

* Statement 클래스내 SQL문 처리 메소드

  - executeQuery() : Select문과 같이 실행 후 화면에 표시될 결과가 있을 때 → 리턴타입 : ResultSet형

  - executeUpdate() : Insert, Update, Delete와 같이 출력 결과가 없을 때

 

 

 

   4. DB 연결 해제하기   

- DB 사용을 종료하면 close() 함수를 호출하여 닫아주어야함

// DB 사용을 종료하여 close() 함수 호출

rs.close();
stmt.close();
db.close();

 

 


 

 

 

 

궁금한 사항은 댓글로 남겨주세요💃💨💫
좋아요와 구독(로그인X)은 힘이 됩니다 🙈🙉

 

반응형
그리드형

댓글

❤️김세인트가 사랑으로 키웁니다❤️