승띵이의 개발일지
[JDBC] JDBC - Insert, Delete, Update (feat. Utilitiy Class) 본문
유틸리티 클래스 (Utility Class)
~Utils 의 명명법을(주로) 가진다. 객체화를 못하도록 막는 것이 일반적이며, 이는 정적이고 상수인 멤버나, 정적인 메서드만 가진다. 주로 자주 사용하는 코드를 서로 관련있는 것들 끼리 묶어내는 역할을 한다.
DatabaseUtils
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseUtils {
public static Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("org.mariadb.jdbc.Driver"); //어디에 접속할 지 알려주는 역할
Connection connection = DriverManager.getConnection
//Connection은 Interface라서 new를 사용하여 만들만 큰일남
("jdbc:mariadb://localhost:12602",
"study",
"test1234");
return connection;
}
}
Insert
name과 age 칼럼을 가진 테이블을 만든 후 사람 이름과 나이를 Insert 하려는 코드를 작성하려고 한다.
(테이블 생성은 생략)
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Insert {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Connection connection = DatabaseUtils.getConnection();
String name = "김잼민";
int age = 12;
System.out.println(connection.isClosed());
//DB 제대로 연결됐는지 확인(false 면 연결된 거)
PreparedStatement preparedStatement = connection.prepareStatement
("insert into study.jdbc (`name`, `age`) values (?, ?)");
preparedStatement.setString(1, name);
preparedStatement.setInt(2, age);
int i = preparedStatement.executeUpdate();
//exexecuteUpdate()를 해야 진짜 쿼리문 실행됨
System.out.println(i); //제대로 실행되면 1 출력
}
}
Delete
Insert로 추가한 레코드 중 김씨 성을 가진 사람만 Delete하는 코드를 작성해보겠다.
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Delete {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Connection conncetion = DatabaseUtils.getConnection();
String lastName = "김%";
System.out.println(connection.isClosed());
PreparedStatement preparedStatement = connection.prepareStatement
("delete from study.jdbc where name like ?");
preparedStatement.setString(1, lastName);
preparedStatement.executeUpdate();
//teacherVer : Use concat();
String familyName = "김";
PreparedStatement preparedStatement1 = connection.prepareStatement
("delete from study.jdbc where name like concat(?, '%')");
preparedStatement1.setString(1, familyName);
int i = preparedStatement1.executeUpdate();
System.out.println(i); //실행된 개수 출력
}
}
나는 처음부터 변수에 %를 사용하여 코드를 작성했는데 강사님은 쿼리문에 concat을 이용하였다..
난 왜 이걸 생각못했지 ㅠ
Update
레코드를 Update하는 클래스를 작성해보았다.
잼민이를 성인으로 만들어 보았다.
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Update {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Connection connection = DatabaseUtils.Connection1();
String oldName = "김잼민";
int newAge = 20;
System.out.println(connection.isClosed());
PreparedStatement preparedStatement = connection.prepareStatement
("update study.jdbc set age = ? where name = ? limit 1");
preparedStatement.setInt(1, newAge);
preparedStatement.setString(2, oldName);
preparedStatement.executeUpdate();
}
}
}
}
'언어 > JDBC' 카테고리의 다른 글
[JDBC] JDBC (Java Database Connectivity) (0) | 2022.10.24 |
---|---|
[JDBC] 메이븐(Maven) (0) | 2022.10.24 |
Comments