먼저, JDBC를 이용해 MySQL과 Java를 연결하는 방법은 아래 게시글을 참조해주세요.

 

mySQL과 Java 연결하기(JDBC 라이브러리)

1. JDBC란? JDBC(Java Database Connectivity)는 Java 기반 애플리케이션의 데이터를 데이터베이스에 저장 및 업데이트하거나, 데이터베이스에 저장된 데이터를 Java에서 사용할 수 있도록 하는 자바 API. JDBC

dogfoot-er.tistory.com

1.바로 실전으로! 

1.1 CREATE TABLE (테이블 만들기)

package main;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.mysql.cj.xdevapi.Result;

import config.DBConnectionMgr;

public class Main2 {

	public static void main(String[] args) {
		
		//우리는 이것을 pool이라고 부르기로 했어요
		DBConnectionMgr pool = DBConnectionMgr.getInstance(); 
		
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		//CREATE TABLE 
		try {
			con = pool.getConnection();
			System.out.println("성공적으로 연결");
			String sql = "CREATE TABLE IF NOT EXISTS TEST_TB("
					+ "`test_id` INT NOT NULL AUTO_INCREMENT,"
					+ "`test_name` VARCHAR(45) NOT NULL,"
					+ "`test_address` VARCHAR(45) NOT NULL,"
					+ "PRIMARY KEY (`test_id`));";
			
			pstmt = con.prepareStatement(sql);
			pstmt.execute();
		} catch(Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt, rs);
		}
		


	}
}

 

 

SQL에 들어가보면 DDL 쿼리문대로 생성 완료!

 

1.2 Insert (값 넣기)

public class Main2 {

	public static void main(String[] args) {
		
		DBConnectionMgr pool = DBConnectionMgr.getInstance(); 
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;

////////  Insert into ////////
		try {
			//DB에 연결
			con = pool.getConnection();
			
			//쿼리문 작성
			String sql = "insert into test_tb values(0, ?, ?)";
			
			//쿼리문 가공준비
			pstmt = con.prepareStatement(sql);
			
			//쿼리문 가공
			pstmt.setString(1,"ShinyDev"); //1번(째 물음표)에 값 저장
			pstmt.setString(2,"https://dogfoot-er.tistory.com/");
			
			//쿼리문 실행
			int successCount = pstmt.executeUpdate();
			System.out.println("\n insert 성공횟수 : " + successCount +"\n");
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt);
		}
    }
}

 

정상 생성 완료 확인!

1.3. select * from( 테이블 조회)

public class Main2 {

	public static void main(String[] args) {
		
		DBConnectionMgr pool = DBConnectionMgr.getInstance(); 
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;

//////// select * from ////////

		try {
			con = pool.getConnection();
			String sql = "select * from test_tb";
			pstmt = con.prepareStatement(sql);
			rs = pstmt.executeQuery();
			System.out.println("번호\t|\t아이디\t|\t비밀번호");
			while(rs.next()) { 
				System.out.println(rs.getInt(1) + "\t|\t" + rs.getString(2) + "\t|\t" + rs.getString(3));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt, rs); 
		}

	}
}

 

콘솔에 정상적으로 출력되었다.

 

 

2. 해설 

2.1 공통부분