
SELECT 열이름 FROM 테이블명 WHERE 조건식
데이터베이스로부터 선택한 열의 정보를 가져올 수 있으며 필요에 따라 조건식을 작성해 해당 조건을 만족하는 값(레코드)만 가져올 수도 있음
*은 전체를 의미함.
USE student_DB
사용할 스키마(schema)를 지정할 수 있음
WHERE stdID LIKE '23%';
필요 시 AND/OR 연산자 역시 사용 가능함
+LIKE는 ~와 비슷한 패턴을 검색하라는 연산자
+%기호: 23으로 시작하고, 그 뒤에 0개 이상의 모든 문자가 오는 문자열 의미
INSERT INTO student (dept, stdID, name) VALUES (?, ?, ?);
-자바에서는 위처럼 작성하고 후에 값을 설정할 수 있었음
UPDATE student
SET name = '김ㅇㅇ'
WHERE no = 1;
DELETE FROM student WHERE no = 5;
try(Connection conn = DriverManager.getConnection(url, user, password) ){
System.out.println("DB 연결 성공!");
String selectSql = "SELECT * FROM student order by no asc";
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery(selectSql);
System.out.println("========================================================");
while (rs.next()) {
int no = rs.getInt("no");
String dept = rs.getString("dept");
String stdID = rs.getString("stdID");
String name = rs.getString("name");
String review = rs.getString("review");
System.out.printf("%2d %10s %10s %10s %s \n", no, dept, stdID, name, review);
}
}
try-catch-finally의 구문에서 finally에서 직접 자원을 close()를 통해 정리해야했다면, 이 자원 정리를 자동으로 대신 처리해 주는 구문임try(...) 소괄호 안에 자원을 해제해줘야하는 구문을 작성 (단, AutoCloseable 인터페이스를 구현한 자원들만 선언 가능)close()는 보장됨일단 맥북 기준으로 실습을 진행했다.
mysql.server start를 통해서 우선 서버를 실행시켜줘야했다...
public static void main(String[] args) {
String url = "jdbc:mysql://127.0.0.1:3306/test";
String user = 사용자이름입력;
String password = 비밀번호입력;
//try-with-resource
try(Connection conn = DriverManager.getConnection(url, user, password) ){
System.out.println("DB 연결 성공!");
String selectSql = "SELECT * FROM student order by no asc";
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery(selectSql);
...
}
Statement 또는 PreparedStatement 객체를 생성Statement: 정적인 SQL문 실행에 사용 String selectSql = "SELECT * FROM student order by no asc";
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery(selectSql);
System.out.println("========================================================");
while (rs.next()) {
int no = rs.getInt("no");
String dept = rs.getString("dept");
String stdID = rs.getString("stdID");
String name = rs.getString("name");
String review = rs.getString("review");
System.out.printf("%2d %10s %10s %10s %s \n", no, dept, stdID, name, review);
}
String insertSql = "INSERT into student (dept, stdID, name, review) VALUES (?,?,?,?)";
PreparedStatement pstmt = conn.prepareStatement(insertSql);
pstmt.setString(1,"컴퓨터공학과");
pstmt.setString(2,"2376097");
pstmt.setString(3,"박서영");
pstmt.setString(4,"JDBC 연결 ");
pstmt.executeUpdate();
System.out.println("JDBC 삽입 성공");
ResultSet 객체에 조회된 데이터의 집합이 반환됨next() 메소드를 호출해 각 행씩 이동하며 데이터를 읽어올 수 있음try-with-resources를 사용하면 자동으로 자원을 해제해줌| 역할 | 클래스이름 | 설명 |
|---|---|---|
| 학생 DAO | StudentDAO | DB와 직접적으로 통신. JDBC 관련 로직 구현, CRUD 메소드 구현 |
| 모델 | Student(DTO) | 학생 테이블의 데이터를 담는 객체. 로직X, getter/setter만 존재 |
| 메인 흐름 | StudentTest | 모든 클래스 조립 및 실행 |
| DB 연결 관리 | DBConnector | DB 연결 정보 관리 및 연결 제공 |
public class StudentDAO {
private final DBConnector dbConnector;
public StudentDAO(DBConnector dbConnector) {
this.dbConnector = dbConnector;
}
//1. 학생 목록 조회하기
public List<Student> getStudentList() {
List<Student> students = new ArrayList<>();
String sql = "SELECT * FROM student order by no asc";
try (Connection conn = dbConnector.getConnection()) {
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
Student student = new Student();
student.setNo(rs.getInt("no"));
student.setDept(rs.getString("dept"));
student.setName(rs.getString("name"));
student.setStdID(rs.getString("stdID"));
students.add(student);
}
} catch (SQLException e) {
e.printStackTrace();
}
return students;
}
//2. 학생 추가하기
public void insertStudent (Student student) {
String sql = "INSERT INTO student (dept, stdID, name) VALUES (?,?,?)";
try (Connection conn = dbConnector.getConnection()) {
PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1, student.getDept());
pstmt.setString(2, student.getStdID());
pstmt.setString(3, student.getName());
pstmt.executeUpdate();
try (ResultSet generatedKeys = pstmt.getGeneratedKeys()){
if (generatedKeys.next()) {
int no = generatedKeys.getInt(1);
student.setNo(no);
System.out.println(no + "학생 정보가 추가되었습니다.");
}
}
}
catch (SQLIntegrityConstraintViolationException e) {
System.out.println("학번은 중복될 수 없습니다.");
}
catch (SQLException e) {
e.printStackTrace();
}
}
//3. 학생 정보 수정하기
public void updateStudent (Student student) {
String sql = "UPDATE student SET dept = ?, name = ?, stdID = ? WHERE no = ?";
try (Connection conn = dbConnector.getConnection()) {
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, student.getDept());
pstmt.setString(2, student.getName());
pstmt.setString(3,student.getStdID());
pstmt.setInt(4,student.getNo());
pstmt.executeUpdate();
} catch (SQLIntegrityConstraintViolationException e) {
System.out.println("학번은 중복될 수 없습니다.");
}
catch (SQLException e) {
e.printStackTrace();
}
System.out.println("성공적으로 수정되었습니다.");
}
//4. 학생 삭제하기
public void deleteStudent (int no) {
String sql = "DELETE FROM student WHERE no=?";
try(Connection conn = dbConnector.getConnection()) {
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1,no);
pstmt.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException(e);
}
System.out.println("성공적으로 삭제되었습니다.");
}
}
public class StudentService {
DBConnector dbConnector = new DBConnector();
StudentDAO dao = new StudentDAO(dbConnector);
Scanner sc = new Scanner(System.in);
public void showStudentList() {
List<Student> studentList = dao.getStudentList();
System.out.println("======================================================");
for (Student s : studentList) {
System.out.printf("NO%d. | 이름: %s | 학번: %s | 학과: %s", s.getNo(), s.getName(), s.getStdID(), s.getDept());
System.out.println();
}
System.out.println("======================================================");
}
public void addStudent() {
System.out.println("추가할 학생 정보를 입력하세요.");
System.out.print("이름: ");
String name = sc.next();
System.out.print("학번: ");
String stdID = sc.next();
System.out.print("학과: ");
String dept = sc.next();
Student s = new Student(dept, stdID, name);
dao.insertStudent(s);
}
public void editStudent() {
showStudentList();
System.out.print("수정할 학생의 NO.를 입력하세요: ");
int no =sc.nextInt();
System.out.print("수정할 이름: ");
String name = sc.next();
System.out.print("수정할 학번: ");
String stdID = sc.next();
System.out.print("수정할 학과: ");
String dept = sc.next();
Student s = new Student(dept, stdID, name);
s.setNo(no);
dao.updateStudent(s);
}
public void deleteStudent() {
showStudentList();
System.out.print("삭제할 학생의 NO.를 입력하세요: ");
int no = sc.nextInt();
dao.deleteStudent(no);
}
}
학생 조회

학생 추가

학생 정보수정

학생 정보삭제

후기
다양한 내용을 한 번에 배운 것 같아서 정리할 필요성을 느꼈던 것 같다. 이전에 DB를 다룰 때는 ORM?을 써서, SQL문이나 직접 DB 테이블을 만들어보거나 JDBC 등을 사용하지 않아서 처음 이런 내용을 접하게 돼서 재밌었다. DB 서버?랑(이 외에도 이전의 네트워크 연결 포함) 연결시키는 방법도 몇 번 하다보니 익숙해져서 괜찮았던 것 같다. 와이파이 바꾸는걸 까먹어서 헤맸다... 궁금했던 점은 현재는 일단 같은 네트워크 안에서 DB를 공유해 사용하는데, 만약 다른 네트워크?에서 DB 서버를 만들어 사용하려면 어떻게 해야할지? 이런 부분에 대해서 생각하게 되었다...