mojo's Blog

JDBC Programming 본문

Java

JDBC Programming

_mojo_ 2021. 8. 24. 18:37

DataBase 연결 설정

 

1. MySQL 서버의 JDBC 드라이버 로드

JDBC 드라이버를 로드하기 위해 드라이버 클래서 파일을 로드한다. 다음과 같이 자바의 Class 클래스의 forName() 메소드를 이용하면 특정 클래스 파일을 읽어 들일 수 있다.

 

try{
    Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}

 

2. 자바 응용프로그램과 JDBC의 연결

 

DriverManager는 자바 응용프로그램을 JDBC 드라이버에 연결해주는 클래스이다.

DriverManager.getConnection() 메소드를 호출하여 데이터베이스에 연결하고 Connection 객체를 반환한다.

 

try{
    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/디비명", "root", "비번");
} catch (SQLException e) {
    e.printStackTrace();
}

 

 

samplesdb 데이터베이스에 연결하는 JDBC 프로그램 작성 코드

 

package Part16;

import java.sql.*;

public class JDBC_EX {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		try {
			Class.forName("com.mysql.cj.jdbc.Driver");	
			String url="jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Seoul";
			
			Connection conn = DriverManager.getConnection(url, "root", "");
			System.out.println("DB 연결 완료");
		} catch(ClassNotFoundException e) {
			System.out.println("JDBC 드라이버 로드 에러");
		} catch(SQLException e) {
			System.out.println("DB 연결 에러");
		}
		
	}

}

 

 

3. 데이터 검색

 

테이블의 모든 데이터를 검색하는 코드

 

Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from student");

 

특정 열만 검색하는 코드

 

ResultSet rs = stmt.executeQuery("select name, id from student");

 

조건 검색 코드

 

Result rs = stmt.executeQuery("select name, id, dept from student where id='0494013'");

 

검색된 데이터의 사용 코드

 

while (rs.next()) {
    System.out.println(rs.getString("name"));
    System.out.println(rs.getString("id"));
    System.out.println(rs.getString("dept"));
}

 

연습 ) 데이터 검색과 출력하는 코드

 

package Part16;

import java.io.*;
import java.sql.*;

public class JDBC_EX {

	private static void printData(ResultSet srs, String col1, String col2, String col3) 
			throws SQLException {
		while(srs.next()) {
			if(col1 != "") System.out.print(new String(srs.getString("name")));
			if(col2 != "") System.out.print("\t|\t" + srs.getString("id"));
			if(col3 != "") System.out.println("\t|\t" + new String(srs.getString("dept")));
			else System.out.println();
		}
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Connection conn = null;
		Statement stmt = null;
		
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");	
			String url="jdbc:mysql://localhost:3306/sampledb?serverTimezone=Asia/Seoul";
			
			conn = DriverManager.getConnection(url, "root", "");
			System.out.println("DB 연결 완료");
			
			stmt = conn.createStatement();
			String sql = "select * from student";
			ResultSet srs = stmt.executeQuery("select * from student");
			printData(srs, "name", "id", "dept");
			
			System.out.println();
			srs = stmt.executeQuery("select name, id, dept from student where name='이기자'");
			printData(srs, "name", "id", "dept");
		} catch(ClassNotFoundException e) {
			System.out.println("JDBC 드라이버 로드 에러");
		} catch(SQLException e) {
			System.out.println("DB 연결 에러");
		}
		
	}

}

 

데이터를 변경하는 코드

 

package Part16;

import java.io.*;
import java.sql.*;

public class JDBC_EX {

	private static void printTable(Statement stmt) throws SQLException {
		ResultSet srs = stmt.executeQuery("select * from student");
		System.out.println("---------------------------");
		while(srs.next()) {
			System.out.print(new String(srs.getString("name")));
			System.out.print("\t|\t" + srs.getString("id"));
			System.out.println("\t|\t" + new String(srs.getString("dept")));
		}
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Connection conn = null;
		Statement stmt = null;
		
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");	
			String url="jdbc:mysql://localhost:3306/sampledb?serverTimezone=Asia/Seoul";
			
			conn = DriverManager.getConnection(url, "root", "");
			System.out.println("DB 연결 완료");
			
			stmt = conn.createStatement();
			stmt.executeUpdate("insert into student (name, id, dept) "
					+ "values('아무개', '0893012', '컴퓨터공학');");
			printTable(stmt);
			
			stmt.executeUpdate("update student set id='0189011' where name='아무개'");
			printTable(stmt);
			
			stmt.executeUpdate("delete from student where name='아무개'");
			printTable(stmt);
			
		} catch(ClassNotFoundException e) {
			System.out.println("JDBC 드라이버 로드 에러");
		} catch(SQLException e) {
			System.out.println("DB 연결 에러");
		}
		
	}

}

Comments