JDBC(Java DataBase Connective)
자바/JSP 프로그램 내에서 DB와 관련된 작업을 처리할 수 있도록 도와주는 자바 표준 인터페이스이다.
JDBC는 다음의 단계로 프로그래밍된다.
- 라이브러리 확보 WEB.INF/lib/MySQL-connector.jar
- java.sql.* 패키지 임포트
- JDBC 드라이버 로딩
- 데이터베이스 접속을 위한 Connection 객체 생성
- 쿼리문을 실행하기 위한 Statement / PreparedStatement 객체 생성
- 쿼리 실행
- 쿼리 실행의 결과 값 사용
- 사용된 객체 종료
JDBC 드라이버 로딩하기
Class.forName(String className); className은 드라이버 이름
Class.forName("com.mysql.jbdc.Driver"); // MySQL 드라이버 로딩
Connection 객체 생성하기
static Connecton getConnection(String url)
static Connecton getConnection(String url, String user, String password)
static Connecton getConnection(String url, Properies info)
Connection conn = null;
try {
Class.forName("com.mysql.jbdc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/DB이름?user=root&password=1234");
} catch(SQLException e) {
e.getMessage();
}
위의 방법으로 커넥션 객체를 생성할 수 있다.
또는 위의 코드에서 getConnection("jdbc:mysql://localhost:3306", "root", "1234"); 의 형태로도 생성이 가능하다.
데이터베이스 연결 닫기
try-catch문 후에 finally를 이용하여 if(conn != null) conn.close();를 해주는게 좋다.
데이터베이스 쿼리 실행
자바에서 SQL을 데이터베이스로 전달하는 과정이다.
쿼리 실행 객체는 Statement 또는 PreparedStatement를 사용한다.
DML에는 select, update, insert, delete가 있다.
이중에서 select는 유일하게 반환데이터가 있기 때문에 혼자만 다른 메서드를 사용한다.
executeQuery() : select 문을 실행할때 사용한다.(ResultSet 객체 반환)
executeUpdate() : 삽입, 수정, 삭제와 관련된 SQL문 실행에 사용된다.
insert, update, delete 쿼리문 사용 예시
<%
Connection conn = null;
(생략)
Statement stmt = conn.createStatment();
String sql = "insert into member (id, name, passwd) values('1', '철수', '1234')"
int rs = stmt.executeUpdate(sql);
%>
<%
Connection conn = null;
(생략)
Statement stmt = conn.createStatment();
String sql = "update member set name = '관리자' where id = '1' "
int rs = stmt.executeUpdate(sql);
%>
<%
Connection conn = null;
(생략)
Statement stmt = conn.createStatment();
String sql = "delete from member where id = '1' "
int rs = stmt.executeUpdate(sql);
%>
위의 코드는 자바에서 SQL을 삽입, 수정, 삭제 하는 방법에 대한 내용이다.
위의 코드들에서는 Statement를 사용했는데, 이때 데이터가 아닌 변수를 집어넣게 되면
String sql = "insert into member(id, passwd, name) values('" + id + "','" + passwd + "','" + name +"')";
이러한 형태로 써야하기 때문에 알아보기가 힘들다 그렇게 때문에 사용하는 것이
PreparedStatement 객체이다.
PraparedStatement stmt = null;
(생략)
String sql = "insert into member(id, passwd, name) values(?,?,?)";
stmt = conn.prparedStatement(sql);
stmt.setString(1, id);
stmt.setString(2, name);
stmt.setString(3, passwd);
이러한 형태로 변수를 사용할때 가독성 좋게 사용할수 있다.
정적 쿼리문에서는 Statement를 사용해도 충분하지만 변수를 이용한 정적 쿼리문에서는 PreparedStatement가 더 가독성이나 코드유지보수에 유용하다.
쿼리문 실행 결과 값 접근
select를 이용해서 위에서 삽입하고 수정하고 삭제한 데이터를 조회하는 방법이다.
<%
Connection conn = null;
(생략)
Statement stmt = conn.createStatment();
String sql = "select * from member where id = '1'"
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
out.print(rs.getString(2) + "," + rs.getString(3) + "<br>");
}
rs.close();
stmt.close()
%>
select로 값을 조회하게 되면 테이블에 있는 데이터중 해당하는 튜플의 컬럼 항목을 모두 가져오기 때문에 묶음의 형태로 데이터를 가져오게 된다.
이 데이터 묶음을 rs 변수에 저장한 후 Enumerator와 비슷한 방법으로 next() 메서드를 이용해서 항목이 있으면 출력하는 방법으로 출력할 수 있다.
또는 dto 형식의 클래스를 만들어서 객체생성한 후 클래스에 담고 ArrayList에 담아서 대량의 select 결과 값을 옮길수도 있다.
'프로그래밍 공부' 카테고리의 다른 글
2025.02.25 MVC패턴 공부 (0) | 2025.02.25 |
---|---|
2025.02.24 MVC패턴 공부 (0) | 2025.02.24 |
2025.02.20 JSP 공부 (0) | 2025.02.20 |
2025.02.19 JSP 공부 (0) | 2025.02.19 |
2025.02.18 JSP 공부 (0) | 2025.02.18 |