16. JDBC로 데이터베이스와 JSP 연동

Yuri Lee·2022년 6월 6일
0

JSP

목록 보기
16/19

< JDBC 의 개요>

자바/JSP 프로그램 내에서 데이터베이스와 관련된 작업을 처리할 수 있도록 도와주는 자바 표준 인터페이스. 관계형 데이터베이스 시스템에 접근하여 SQL문을 실행하기 위한 자바 API 또는 자바 라이브러리이다.

< JDBC 드라이버 로딩 및 DBMS 접속>

  • JDBC 드라이버 로딩 단계에서는 드라이버 인터페이스를 구현하는 작업으로 Class, forName() 메소드를 이용하여 JDBC 드라이버를 로딩한다. JDBC 드라이버가 로딩되면 자동으로 객체가 생성되고 DriverManager 클래스에 등록된다.
  • JDBC 드라이버에서 데이터 베이스와 연결된 커넥션을 가져오기 위해 DriverManager 클래스의 getConnection() 메소드를 사용
  • 데이터베이스 연결이 더 이상 필요하지 않으면 데이터베이스와 JDBC 리소스가 자동으로 닫힐 때까지 대기하는 게 아니라, close() 메소드로 Connection 객체를 해제한다.

dbconn.jsp

<%@ page contentType="text/html; charset=utf-8"%>
<%@ page import="java.sql.*" %>

	<%
		Connection conn=null;
	
		try{
			String url = "jdbc:mysql://localhost:3306/webmarketDB?serverTimezone=Asia/Seoul&useSSL=false";
			String user = "root";
			String password = "1234";
			
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(url,user,password);
		}catch(SQLException ex){
			out.println("데이터베이스 연결이 실패했습니다.");
			out.println("SQLException:"+ex.getMessage());
		}
	%>

<데이터베이스 쿼리 실행>

  • Statement 객체는 정적인 쿼리에 사용
    - executeQuery() 메소드는 정적인 SELECT 쿼리문을 통해 데이터를 검색하는 데 사용
    • executeUpdate() 메소드는 insert, update, select 쿼리문을 통해 데이터를 삽입, 수정, 삭제하는 데 사용
  • PreparedStatement 객체는 동적인 쿼리에 사용
    - executeQuery() 메소드는 동적인 select 쿼리문을 통해 데이터를 검색하는 데 사용
    • executeUpdate() 메소드는 insert, update, select 쿼리문을 통해 데이터를 삽입, 수정, 삭제하는 데 사용
	
	PreparedStatement pstmt = null;
	
	String sql = "insert into product values(?,?,?,?,?,?,?,?,?)";
	pstmt = conn.prepareStatement(sql);
	
	pstmt.setString(1,productId);
	pstmt.setString(2,name);
	pstmt.setInt(3,price);
	pstmt.setString(4,description);
	pstmt.setString(5,category);
	pstmt.setString(6,manufacturer);
	pstmt.setLong(7,stock);
	pstmt.setString(8,condition);
	pstmt.setString(9,fileName);
	
	pstmt.executeUpdate();
	
	if(pstmt !=null)
		pstmt.close();
	if(conn !=null)
		conn.close();

<쿼리문 실행 결과 값 가져오기>

  • statement 객체를 사용하는 경우
ResultSet executeQuery(String sql) throws SQLException
  • PreparedStatement 객체를 사용하는 경우
ResultSet executeQuery() throws SQLException
profile
개발자 이유리

0개의 댓글