JDBC
- 자바를 이용한 데이터베이스 접속과 SQL 문장의 실행, 그리고 실행 결과로 얻어진 데이터의 핸들링을 제공하는 방법과 절차에 관한 규약
- 자바 프로그램 내에서 SQL문을 실행하기 위한 자바 API
- SQL과 프로그래밍 언어의 통합 접근 중 한 형태
- JAVA는 표준 인터페이스인 JDBC API를 제공
- 데이터베이스 벤더, 또는 기타 써드파티에서는 JDBC 인터페이스를 구현한 드라이버(driver)를 제공한다.
JDBC를 이용한 프로그래밍 방법
순서중요!!
- import java.sql.*;
- 드라이버를 로드 한다.
- Connection 객체를 생성한다.
- Statement 객체를 생성 및 질의 수행
- SQL문에 결과물이 있다면 ResultSet 객체를 생성한다.
- 모든 객체를 닫는다.
JDBC 단계별 설명
- import
import java.sql.*;
- 드라이버 로드
Class.forName( "com.mysql.jdbc.Driver" );
- Connection 얻기
String dburl = "jdbc:mysql://localhost/dbName";
Connection con = DriverManager.getConnection ( dburl, ID, PWD );
소스코드 예제
public static Connection getConnection() throws Exception{
String url = "jdbc:oracle:thin:@117.16.46.111:1521:xe";
String user = "smu";
String password = "smu";
Connection conn = null;
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, user, password);
return conn;
}
- Statement 생성
Statement stmt = con.createStatement();
- 질의 수행
ResultSet rs = stmt.executeQuery("select no from user" );
참고
stmt.execute(“query”); //any SQL
stmt.executeQuery(“query”); //SELECT
stmt.executeUpdate(“query”); //INSERT, UPDATE, DELETE
- ResultSet으로 결과 받기
ResultSet rs = stmt.executeQuery( "select no from user" );
while ( rs.next() )
System.out.println( rs.getInt( "no") );
- Close (
순서는 앞에와 반대로!!
)
rs.close();
stmt.close();
con.close();
소스코드 예제
public List<GuestBookVO> getGuestBookList(){
List<GuestBookVO> list = new ArrayList<>();
GuestBookVO vo = null;
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
conn = DBUtil.getConnection();
String sql = "select * from guestbook";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()){
vo = new GuestBookVO();
vo.setNo(rs.getInt(1));
vo.setId(rs.getString(2));
vo.setTitle(rs.getString(3));
vo.setConetnt(rs.getString(4));
vo.setRegDate(rs.getString(5));
list.add(vo);
}
}catch(Exception e){
e.printStackTrace();
}finally {
DBUtil.close(conn, ps, rs);
}
return list;
}
public int addGuestBook(GuestBookVO vo){
int result = 0;
Connection conn = null;
PreparedStatement ps = null;
try{
conn = DBUtil.getConnection();
String sql = "insert into guestbook values("
+ "guestbook_seq.nextval,?,?,?,sysdate)";
ps = conn.prepareStatement(sql);
ps.setString(1, vo.getId());
ps.setString(2, vo.getTitle());
ps.setString(3, vo.getConetnt());
result = ps.executeUpdate();
}catch(Exception e){
e.printStackTrace();
}finally {
DBUtil.close(conn, ps);
}
return result;
}
public static void close(Connection conn, PreparedStatement ps){
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {e.printStackTrace(); }
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {e.printStackTrace();}
}
}
JDBC 예제
Role.java
package kr.or.connect.jdbcexam.dto;
public class Role {
private Integer roleId;
private String description;
public Role() {
}
public Role(Integer roleId, String description) {
super();
this.roleId = roleId;
this.description = description;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return "Role [roleId=" + roleId + ", description=" + description + "]";
}
}
RoleDao.java - 기존 값 Query
package kr.or.connect.jdbcexam.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import kr.or.connect.jdbcexam.dto.Role;
public class RoleDao {
private static String dburl = "jdbc:mysql://localhost:3306/connectdb";
private static String dbUser = "connectuser";
private static String dbpasswd = "connect123!@#";
public Role getRole(Integer roleId) { // role 중에서 하나만 가져온다
Role role=null;
Connection conn =null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(dburl, dbUser, dbpasswd);
String sql = "SELECT role_id, description FROM role WHERE role_id=?";
ps=conn.prepareStatement(sql);
ps.setInt(1, roleId); // ?에 해당하는 값
rs=ps.executeQuery();
if(rs.next()) { //결과값이 있다면 첫번째 레코드로 커서를 이동시키고 true를 return해줘요, 만약 없다면 false return 해줘요
int id = rs.getInt("role_id");
String description = rs.getString(2);
role = new Role(id, description);
}
}catch (Exception e) {
e.printStackTrace();
}finally { //일단 try catch 하든말든 위에 객체들 닫아주자!
if(rs!=null) { //Connection 또는 PreparedStatement에서 예외발생하면 rs는 null포인터 exception
try {
rs.close();
}catch (SQLException e) {
e.printStackTrace();
}
}
if(ps!=null) {
try {
ps.close();
}catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null) {
try {
conn.close();
}catch (SQLException e) {
e.printStackTrace();
}
}
}
return role;
}
}
JDBCExam01.java - 기존값 Query
package kr.or.connect.jdbcexam;
import kr.or.connect.jdbcexam.dao.RoleDao;
import kr.or.connect.jdbcexam.dto.Role;
public class JDBCExam01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
RoleDao dao = new RoleDao();
Role role = dao.getRole(100);
System.out.println(role);
}
}
RoleDao.java - Insert
- 위의 RoleDao.java 코드와 다른 점은 Finally 절이 없다
- try문 안에 conn 객체, ps객체를 넣음으로서
자동으로 close 시켜줌
package kr.or.connect.jdbcexam.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import kr.or.connect.jdbcexam.dto.Role;
public class RoleDao {
private static String dburl = "jdbc:mysql://localhost:3306/connectdb";
private static String dbUser = "connectuser";
private static String dbpasswd = "connect123!@#";
public int addRole(Role role) {
int insertCount = 0;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String sql = "INSERT INTO role (role_id, description) VALUES ( ?, ? )";
try (Connection conn = DriverManager.getConnection(dburl, dbUser, dbpasswd);
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, role.getRoleId());
ps.setString(2, role.getDescription());
insertCount = ps.executeUpdate();
} catch (Exception ex) {
ex.printStackTrace();
}
return insertCount;
}
}
JDBCExam02.java - Insert
package kr.or.connect.jdbcexam;
import kr.or.connect.jdbcexam.dao.RoleDao;
import kr.or.connect.jdbcexam.dto.Role;
public class JDBCExam2 {
public static void main(String[] args) {
int roleId = 501;
String description = "CTO";
Role role = new Role(roleId, description);
RoleDao dao = new RoleDao();
int insertCount = dao.addRole(role);
System.out.println(insertCount);
}
}
RoleDao.java - SELECT
- role들을 여러개 가져오기
package kr.or.connect.jdbcexam.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import kr.or.connect.jdbcexam.dto.Role;
public class RoleDao {
private static String dburl = "jdbc:mysql://localhost:3306/connectdb";
private static String dbUser = "connectuser";
private static String dbpasswd = "connect123!@#";
public List<Role> getRoles() {
List<Role> list = new ArrayList<>();
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String sql = "SELECT description, role_id FROM role order by role_id desc";
try (Connection conn = DriverManager.getConnection(dburl, dbUser, dbpasswd);
PreparedStatement ps = conn.prepareStatement(sql)) {
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
String description = rs.getString(1);
int id = rs.getInt("role_id");
Role role = new Role(id, description);
list.add(role); // list에 반복할때마다 Role인스턴스를 생성하여 list에 추가한다.
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return list;
}
}
JDBCExam03.java - SELECT
package kr.or.connect.jdbcexam;
import java.util.List;
import kr.or.connect.jdbcexam.dao.RoleDao;
import kr.or.connect.jdbcexam.dto.Role;
public class JDBCExam3 {
public static void main(String[] args) {
RoleDao dao = new RoleDao();
List<Role> list = dao.getRoles();
for(Role role : list) {
System.out.println(role);
}
}
}