반응형

개요

 

이번엔는 mariaDB를 이용하여 JDBC에 연결하고 DB를 조작하는 방법에 대해서 알아보도록 하겠습니다.

 


설명

 

mariaDB는 명령어 형식이 mysql과 비슷하므로 아래 링크에서 보시면 됩니다.

jung-story.tistory.com/37?category=827598

 

mysql (mysql 기본 명령어 정리)

이번에는 mysql을 사용할 때 가끔 명령어들이 기억이 나지 않을 경우가 있습니다. 그럴 경우 참고하기 위해서 자주 사용하는 명령어들을 정리해보도록 하겠습니다. . . . 데이터베이스 목록 보기

jung-story.tistory.com

 

 

JDBC를 구성하는 곳에는 대표적으로 3개가 자주쓰입니다.

1. Connection

2. Statement

3. ResultSet

 


Connection 이란?

 

Connection은 데이터베이스와의 연결을 위한 코드

Connection conn = DriverManerger.getConnection(URL, userID, Password);

의 형태를 가집니다.

 

여기서 URL은 "jdbc:mariadb://{host}:{port}/{database}"의 구조를 가집니다.

 


Statement 이란?

 

SQL문을 데이터베이스로 전송합니다.

Statement stmt = conn.createStatement();로 생성한 후 쿼리를 실행합니다.

이후에는 쿼리를 execute 함 - stmt.execute...()

- executeQuery() : select에서만 사용하며, 데이터를 결과로 반환함. 결과를 ResultSet에 저장해줍니다.

- executeUpdate() : Insert, Delete, Update 및 DDL문에 사용하며 결과를 int로 반환합니다.

- execute() : 모든 경우에 사용 가능하며, 결과를 boolean값으로 반환합니다.

 

사용 방법

conn = DriverManager.getConnection(jdbcDriver, dbUser, dbPass);

(DB Connection 생성)

여기서 dbUser와 dbPass는 자신의 DB를 기준으로 설정해주시면 됩니다.

 

stmt = conn.createStatement();

(Statement 생성)

 

result = stmt.executeQuery(query);

(Query 생성)

 


ResultSet 이란?

 

Query의 결과를 반환합니다. (select)

결과 데이터의 현재 행을 가리키는 커서를 유지하며, next()를 이용하여 다음 줄로 이동합니다.

getString()과 getInt() 등을 이용하여 값을 java 변수에 할당합니다 : getType()

getType()의 () 안에 coulmindex(1부터 시작) 하거나 columName를 입력하여 사용합니다.

 

사용 방법

result = stmt.executeQuery(query);

while(result.next()) {

System.out.println(result.getString(1));

}

 

 

작업을 할 때 모든 작업이 다 끝나면 ResultSet, Statement, Connection을 close 해야 합니다.

result.close();

stmt.close();

conn.close();

 

여기서 주의할 것은 순서를 지켜서 close를 해야 합니다.

 

 

위의 3개를 활용하여 제 mariaDB에 접근하고 컨트롤하는 방법에 대해서 알아보겠습니다.

 

 

제가 만든 DB에는 아래와 같은 데이터들이 들어 있습니다.

instructor 테이블

 


(JDBC)

 

 

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

public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Connection conn = null;
		Statement stmt = null;
		ResultSet result = null;
		
		try {
			String jdbcDriver = "jdbc:mariadb://localhost:3306/bookstore";
			String dbUser = "자신의 DB아이디";
			String dbPass = "자신의 DB비밀번호";
			conn = DriverManager.getConnection(jdbcDriver,dbUser,dbPass);
			stmt = conn.createStatement();
			
			String query = "select id from instructor where salary >=60000;";
			String query2 = "select name from instructor where dept_name='Finance';";
			result = stmt.executeQuery(query);
			while(result.next()) {
				int id = result.getInt("ID");
				System.out.println("instructor 테이블에서 salary가 60000 이상인 교수의 ID를 출력 = "+id);
			
			}
			result = stmt.executeQuery(query2);
			while(result.next()) {
				String name = result.getString("name");
				System.out.println("instructor 테이블에서 Finance 학과의 교수 이름을 출력 =  "+name);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				conn.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}

}

 


위의 코드에 대한 결과

 

결과

 

 

이렇게 JDBC에 대해서 간단히 알아보았으며 다음번에는

html과 함께 사용되는 JSP에 대해서 학습을 진행하도록 하겠습니다.

 


 

반응형

+ Recent posts