| 개요
📌 사전 개념 - 5가지 정보 준비, 드라이버 로드, Statement/Preparedstatement/Callablestatement 📌 데이터 CRUD하는 방법 |
| 사전 개념
1. 드라이버 로드
- JDBC API는 앞서 말했듯 라이브러리이다.
- JDBC driver는 이 JDBC 내에서도 특정 JDBC와 연결할 수 있는 클래스이다.
- 따라서, JDBC를 통해 DB를 연결하려면 JDBC Driver 클래스를 로드하는게 필요하다.
try{
Class.forName("패키지명.클래스명");
} catch(ClassNotFountException e) {
e.printStackTrace();
}
[ Driver 클래스의 패키지명을 알아내는 방법 ]
- 아래와 같이 Driver클래스를 라이브러리에서 찾아 소스코드를 보는 방법이 있다.
2. 5가지 정보를 통한 연결
// 5가지 정보를 아래와 같이 미리 문자열에 담는다.
String url = "jdbc:mariadb://ip주소:port/instance";
String dbUserId = "user";
String dbPassword = "password";
// 생략
// DriverManager를 통해 Connection객체로 5가지 정보를 담아 연결한다.
Connection connection = DriverManager.getConnection(url, dbUserId, dbPassword);
3. Statement / PreparedStatement / CallableStatement
- Statement는 말그대로 쿼리문을 실행시켜주는 객체이다.
- 이 객체는 시간이 지나면서 보안 및 기타 이슈를 보완하며 발전했는데,
아래를 보면 알 수 있듯 PreparedStatement를 사용하면 쿼리문에 Parameter를 넣어 전송이 가능하다.
Statement | PreparedStatement | CallableStatement | |
쿼리문 받는 시점 | 실행 시에 | 생성 시에 | 생성 후에 |
parameter설정 | X | O | O |
보안/특성 | SQL Injection 가능성 | SQL Injection 막음 | Stored Procedure를 위해 사용 |
- SQL Injection이란, GET방식을 사용한 URL문에 아래와 같이 특정 문구를 넣어 데이터를 갈취할 수 있도록 하는 해킹 방법을 말한다.
https://www.hello.com/?query=name or 1 = 1 // or 1 = 1 을 추가
| 데이터 CRUD 처리하기
- 전체적인 코드 작성 순서는 다음과 같다.
1. 드라이버 로드 2. 커넥션 객체 생성 3. Statement객체 생성 4. 쿼리 실행 5. 결과 수행 6. 연결 해제 |
- 데이터 CRUD 각 방식에 따라서 조금씩 차이가 있는데, 큰 차이는 없다.
READ | 실행 시 executeQuery() | ResultSet으로 데이터 목록을 받는다. |
CREATE | 실행 시 executeUpdate() | 정상/비정상 여부를 정수형으로 받는다 |
UPDATE | ||
DELETE |
1. READ - 조회하기
import java.sql.*;
public class DBTest {
public void select(String inserted_id) {
// 5가지 연결 정보 사전 준비
String url = "jdbc:mariadb://ip주소:포트/member_db";
String dbUserId = "계정명";
String dbUserPassword = "비밀번호";
// 1. 드라이버 로드
try {
Class.forName("org.mariadb.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet rs = null;
try {
// 2. 커넥션 객체 생성
connection = DriverManager.getConnection(url, dbUserId, dbUserPassword);
// 3. Statement 객체 생성
String sql = "select user_id, name, mobile_no from member where user_id = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, inserted_id);
// 4. 쿼리 실행
rs = preparedStatement.executeQuery();
// 5. 결과 수행
while (rs.next()) {
String user_id = rs.getString("user_id");
String name = rs.getString("name");
String mobile_no = rs.getString("mobile_no");
System.out.printf("%s(%s)님의 휴대폰 번호는 %s입니다.\n", name, user_id, mobile_no);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 6. 연결 해제
try {
if (rs != null && !rs.isClosed()){
rs.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
try {
if (preparedStatement != null && preparedStatement.isClosed()) {
preparedStatement.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
try {
if (connection != null && !connection.isClosed()) {
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
}
2. CREATE - 생성하기
* 입력받는 객체 정보는 앞서 회원정보 테이블 만들때 만들었던 Member 객체를 사용했다.
import java.sql.*;
public class DBTest {
public void insert(MemberVo vo){
// 5가지의 정보
// ip(domain), port, 계정, 패스워드, 인스턴스
String url = "jdbc:mariadb://ip:port/member_db";
String dbUserId = "계정명";
String dbPassword = "비밀번호";
try {
Class.forName("org.mariadb.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DriverManager.getConnection(url, dbUserId, dbPassword);
String sql =
"insert into member" +
"(user_id, password, name, birth, sex, mobile_no, email, location_based_yn, promotion_yn)" +
"values" +
"(?, ?, ?, ?, ?, ?, ?, ?, ?)\n";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, vo.getUser_id());
preparedStatement.setString(2, vo.getPassword());
preparedStatement.setString(3, vo.getName());
preparedStatement.setString(4, vo.getBirth());
preparedStatement.setString(5, vo.getSex());
preparedStatement.setString(6, vo.getMobile_no());
preparedStatement.setString(7, vo.getEmail());
preparedStatement.setBoolean(8, vo.isLocation_based_yn());
preparedStatement.setBoolean(9, vo.isPromotion_yn());
int affected = preparedStatement.executeUpdate();
if (affected > 0) {
System.out.println("저장 성공");
} else {
System.out.println("저장 실패");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (preparedStatement != null && !preparedStatement.isClosed()) {
preparedStatement.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
try {
if (connection != null && !connection.isClosed()) {
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
}
3. UPDATE - 갱신하기
import java.sql.*;
public class TestDB{
public void update(String inserted_id){
// 5가지의 정보
// ip(domain), port, 계정, 패스워드, 인스턴스
String url = "jdbc:mariadb://172.30.1.18:3306/member_db";
String dbUserId = "testuser2";
String dbPassword = "zerobase";
try {
Class.forName("org.mariadb.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DriverManager.getConnection(url, dbUserId, dbPassword);
String sql =
"update member\n" +
"set location_based_yn = false\n" +
"where user_id = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, inserted_id);
int affected = preparedStatement.executeUpdate();
if (affected > 0) {
System.out.println("업데이트 성공");
} else {
System.out.println("업데이트 실패");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (preparedStatement != null && !preparedStatement.isClosed()) {
preparedStatement.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
try {
if (connection != null && !connection.isClosed()) {
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
}
4. DELETE - 삭제하기
public class DBTest{
public void delete(String inserted_id){
// 5가지의 정보
// ip(domain), port, 계정, 패스워드, 인스턴스
String url = "jdbc:mariadb://172.30.1.18:3306/member_db";
String dbUserId = "testuser2";
String dbPassword = "zerobase";
try {
Class.forName("org.mariadb.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DriverManager.getConnection(url, dbUserId, dbPassword);
String sql =
"delete from member\n" +
"where user_id = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, inserted_id);
int affected = preparedStatement.executeUpdate();
if (affected > 0) {
System.out.println("삭제 성공");
} else {
System.out.println("삭제 실패");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (preparedStatement != null && !preparedStatement.isClosed()) {
preparedStatement.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
try {
if (connection != null && !connection.isClosed()) {
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
}
| CRUD에서 사용했던 select/insert/update/delete에 대하여
- 앞서서 회원정보 처리 클래스를 만들 때 register(), withdraw(), getList() 메소드를 만들었었다.
https://why-dev.tistory.com/233?category=962685
- 위에서 사용했던 메소드들을
- insert 는 register(), delete는 withdraw(), select는 getList() 와 같이 메소드명을 구상했던 모델에 맞게 추상화할 수 있다.
[ 출처 및 참고 ]
- 부트캠트 수업을 들은 후 정리한 내용입니다.
- CallableStatement https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=naomi007&logNo=10017208097
'Java, Spring > 웹프로그래밍 시작하기' 카테고리의 다른 글
[웹 프로그래밍] 톰캣 설치 및 이클립스 환경 설정(+톰캣 구조) (0) | 2022.08.28 |
---|---|
[웹 프로그래밍] 서버와 웹 서버, WAS (0) | 2022.08.28 |
[자바 프로그래밍] JDBC 설치하기 (0) | 2022.08.27 |
[자바 프로그래밍] DB연결을 위해 필요한 것 (0) | 2022.08.27 |
[자바 프로그래밍] 회원정보와 회원가입처리 클래스 (0) | 2022.08.27 |