<한줄요약>

JDBC : JAVA에서 Database에 관계 없이 DB연결 및 조작이 가능하다

 

1. JDBC란?

 

-  Java 코드에서 DB에 연결해 SQL문을 실행하고, 결과를 받을 수 있는 API

-  Database 종류에 상관없이, 독립적으로 돌아간다 ( Database별 driver만 바꾸면 된다 )

-  java.sql 내부에 작성되어있다

 

 

2. DB에 연결

 

-  DataBase별 driver 설정

-  DBMS와 연결

-  SQL 생성, 전처리

-  SQL 실행

-  DBMS 연결 종료

 

-  위 5단계로 진행된다

 

-  insert, update, delete 요청은 executeUpdate로 실행, 변경 데이터 갯수를 int로 반환

-  select 요청은 executeQuery로 실행, 검색 데이터를 ResultSet으로 반환한다 

-  ResultSet의 데이터는 while(rs.next())로 주회 가능하며, rs.getInt | getString ("DB 컬럼명") 으로 얻을 수 있다

 

// insert 예제

//id, depary, salary는 인자로 넘어온다고 가정

String URL = "database URL";
String ID = "db ID";
String PW = "db PW";
Connection conn = null;
PreparedStatement pstmt = null;
int rs=0;
try {
	//1. driver 설정
	Class.forName(com.mysql.cj.jdbc.Driver); //mysql 기준 driver
	//2. DBMS 연결
	conn = DriverManager.getConnection(URL,ID,PW);
	//3. SQL 생성, 전처리
	StringBuilder insertMember = new StringBuilder();
	insertMember.append("insert into emp (id, depart, salary) \n");
	insertMember.append("values (?, ?, ?)");
	pstmt = conn.prepareStatement(insertMember.toString());
	//SQL문의 ?부분을 변수의 값으로 치환한다 
	pstmt.setString(1, id);
	pstmt.setString(2, depart);
	pstmt.setString(3, salary);
	//4. SQL실행, 결과반환
	rs=pstmt.executeUpdate();
	if(rs==1){
		System.out.println("성공");
	}
}finally {
	//5. 종료 
	close(pstmt, conn);	
}

public static void close(AutoCloseable ... closeables) {
	try {
		for(AutoCloseable autoC : closeables)
			if(autoC != null)
				autoC.close();
	} catch (Exception e) {
		e.printStackTrace();
	}
}

 

// select 결과 처리 예제

List<EmpDto> list = new ArrayList<>();
rs = pstmt.executeQuery();
while(rs.next()) {
	EmpDto empdto = new EmpDto();
	empdto.setArticleno(rs.getInt("id"));
	empdto.setUserid(rs.getString("depart"));
	empdto.setSubject(rs.getInt("salary"));
	list.add(empdto);
}

 

'WEB 공부' 카테고리의 다른 글

[WEB] Cookie & Session  (0) 2021.05.16
[WEB] Backend - EL, JSTL  (0) 2021.05.16
[WEB] Backend - Servlet, JSP  (0) 2021.05.16
[WEB] Frontend - Bootstrap  (0) 2021.05.15
[WEB] Frontend - AJAX  (0) 2021.05.15
[WEB] Frontend - JQuery  (0) 2021.05.09
[WEB] Frontend - JavaScript, WebBrowser  (0) 2021.05.08

+ Recent posts