MySql를 이클립스 연동을 통해 테이블 입력/수정/조회/삭제 구현하기

DevSeoRex·2022년 5월 29일
0

MySql

목록 보기
4/5

가장 먼저 Connection 객체를 반환하는 getConnection2 클래스를 작성하였다.

public class GetConnection2 {
	public  static Connection getCon() {
		Connection conn = null;
		String driver = "com.mysql.cj.jdbc.Driver";
		String url = "jdbc:mysql://localhost:3306/";
		String dbname = "";
		String id = "";
		String pwd = "";
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url+dbname, id, pwd);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
}

이렇게 작성하여, 매번 다른 클래스에서 Connection을 별도로 생성하지 않아도 이 클래스의 static method getCon을 통해서 생성된 Connection 객체를 return하게 하였다.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Scanner;
public class JDBC_Insert {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String sql = "INSERT INTO Student(name,kor,eng,mat) VALUES(?,?,?,?)";
		Connection con = GetConnection2.getCon();
		PreparedStatement pstmt = null;
		try {
			pstmt = con.prepareStatement(sql);
			System.out.println("이름 : ");
			String name = sc.next();
			System.out.println("국어점수 : ");
			int kor = sc.nextInt();
			System.out.println("영어점수 : ");
			int eng = sc.nextInt();
			System.out.println("수학점수 : ");
			int mat = sc.nextInt();
			pstmt.setString(1, name);
			pstmt.setInt(2, kor);
			pstmt.setInt(3,eng);
			pstmt.setInt(4, mat);
			int cnt = pstmt.executeUpdate();
			System.out.println(cnt + "건이 실행되었습니다.");
			} 
		catch (Exception e) {System.out.println(e.getMessage());}
		finally {
			try {
				pstmt.close();
				con.close();
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
	}
}

Connection 객체를 GetConnection2.getCon() 메소드를 통해서
리턴받고, Scanner를 통해 입력받은 값을 쿼리문을 통해서
DB에 저장하는 코드이다.
int cnt 변수를 통해서 몇건이 삽입되었는지 확인할 수 있다.

public class JDBC_Select {
	public static void main(String[] args) {
		String sql = "SELECT * FROM Student";
		Connection con = GetConnection2.getCon();
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			pstmt = con.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while(rs.next()) {
				String name = rs.getString("name");
				int kor = rs.getInt("kor");
				int eng = rs.getInt("eng");
				int mat = rs.getInt("mat");
				System.out.println("이름 : " + name);
				System.out.println("국어점수 : " + kor);
				System.out.println("영어점수 : " + eng);
				System.out.println("수학점수 : " + mat);
				System.out.println();
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}finally {
			try{
				rs.close();
				pstmt.close();
				con.close();
			}catch(Exception e) {
				e.printStackTrace();
			}
	}
}
    }

위와 동일하지만 테이블을 조회하는 코드다. (select)

public class JDBC_Delete {
	public static void main(String[] args) {
		String sql = "DELETE FROM Student WHERE NAME=?";
		Scanner sc = new Scanner(System.in);
		Connection con = GetConnection2.getCon();
		PreparedStatement pstmt = null;
		try {
			pstmt = con.prepareStatement(sql);
			System.out.println("삭제할 이름을 선택해주세요");
			pstmt.setString(1,sc.next());
			int result = pstmt.executeUpdate();
			if(result !=0 ) {
				System.out.println(result + "건이 삭제되었습니다.");
			}else {
				System.out.println("삭제가 실패하였습니다.");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			if(con != null) {
				try {
					con.close();
				} catch (SQLException e) {
				}
			}if(pstmt != null) {
				try {
					pstmt.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

이름을 입력받아 해당 이름과 일치하는 이름이 있으면 삭제하는 코드이다.

public class JDBC_Update {
	public static void main(String[] args) {
		String sql = "UPDATE Student SET NAME='개발자' WHERE NAME=?";
		Connection conn = GetConnection2.getCon();
		Scanner sc = new Scanner(System.in);
		PreparedStatement pstmt = null;
		try {
			pstmt = conn.prepareStatement(sql);
			System.out.println("변경할 이름을 선택하세요");
			pstmt.setString(1, sc.next());
			int count = pstmt.executeUpdate();
			System.out.println(count + "건이 실행되었습니다.");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

입력받은 이름과 일치하는 이름이 있으면 "개발자"로 이름을 업데이트 해주는 코드이다.

oracle 클라우드를 사용하다가 알 수 없는 이유로 데이터베이스가 삭제된 후에 mysql을 설정한다고 오늘 꽤나 많은 시간을 투자했다.
여러 오류를 만났지만 그래도 배운점이 많아서 기뻤다.

0개의 댓글