ResultSet
ResultSet은 조회한 결과 값에 순차적으로 접근할 수 있는 커서를 제공, 데이터베이스 내부적으로 수행된 SQL문 처리 결과를 JDBC에서 쉽게 관리할 수 있도록 해주는 JAVA 객체이다.
executeUpdate() 메서드 호출 시 반환되는 객체로 실제 데이터를 가지고 있는 것이 아니라, SELECT 문의 결과에 접근할 수 있는 일종의 포인터로 이해해야 한다.
ResultSet rs = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM book");
while (rs.next()) {
int no = rs.getInt("no");
String title = rs.getString("title");
int price = rs.getInt("price");
System.out.println(no);
System.out.println(title);
System.out.println(price);
System.out.println();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeResultSet(rs);
closeStatement(stmt);
closeConnection(conn);
}
*rs.getMetaData() → 테이블 정보
static import
일반적인 import와는 다르게 메소드나 변수를 패키지, 클래스명 없이 접근가능하게 해준다.
클래스 내에 동일한 이름의 메소드나 필드가 있으면 클래스 자신의 메소드를 우선하므로 주의해야한다.
import static dbutil.ConnectionProvider.*;
static block(정적 블럭)
클래스가 로딩되고 클래스 변수가 준비된 후 자동으로 실행되는 블록
한 클래스 안에 여러 개의 static 블록을 넣을 수 있다.
용도 : 주로 클래스 변수를 초기화시키는 코드를 둔다.
*클래스 로드 시점 → 클래스를 사용하려고 하는 시점
JVM에 의해서 클래스 안의 정적 메소드나 필드를 사용하기위해 준비를 해놓는과정에서 정적 블럭이 실행된다.
한번로드된 클래스는 그 이후에는 JVM이 알고있어서 다시 로드를 하지않는다.
CRUD
CRUD는 대부분의 컴퓨터 소프트웨어가 가지는 기본적인 데이터 처리 기능인 Create(생성), Read(읽기), Update(갱신), Delete(삭제)를 묶어서 일컫는 말이다. 사용자 인터페이스가 갖추어야 할 기능(정보의 참조/검색/갱신)을 가리키는 용어로서도 사용된다.
*데이터베이스 SQL문과 대응
이름 | 조작 | SQL |
Create | 생성 | INSERT |
Read(또는 Retrieve) | 읽기(또는 인출) | SELECT |
Update | 갱신 | UPDATE |
Delete(또는 Destroy) | 삭제(또는 파괴) | DELETE |
연습 - book
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import static dbutil.ConnectionProvider.*;
// 데이터베이스 your_db에 접속해
// book table 생성하기
/*
no int PRIMARY KEY
title varchar(25)
price int
*/
public class Main2 {
public static void createBookTable() {
Connection conn = makeConnection();
Statement stmt = null;
try {
stmt = conn.createStatement();
int result = stmt.executeUpdate("CREATE TABLE IF NOT EXISTS book ("
+ " no int PRIMARY KEY"
+ ", title varchar(25)"
+ ", price int)");
System.out.println("결과값: " + result);
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeStatement(stmt);
closeConnection(conn);
}
}
public static int insertBook(int no, String title, int price) {
Connection conn = makeConnection();
Statement stmt = null;
try {
stmt = conn.createStatement();
int result = stmt.executeUpdate("INSERT INTO book (no, title, price)"
+ "VALUES (" + no + ", '" + title + "', " + price + ")");
return result;
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 접속해제
closeStatement(stmt);
closeConnection(conn);
}
return 0;
}
// 책 테이블 : pk값을 전달받아 한 행 삭제하는 명령 수행
public static int deleteBook(int no) {
Connection conn = makeConnection();
Statement stmt = null;
try {
stmt = conn.createStatement();
int result = stmt.executeUpdate("DELETE FROM book WHERE no = " + no);
return result;
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 접속해제
closeStatement(stmt);
closeConnection(conn);
}
return 0;
}
// 책 테이블 : 한 행 수정하기. pk 값으로 검색하여 새 제목, 새 가격으로 변경해보기
public static int updateBook(int no, String title, int price) {
Connection conn = makeConnection();
Statement stmt = null;
try {
stmt = conn.createStatement();
String sql = "UPDATE book SET title = '" + title
+ "', price = " + price + " WHERE no = " + no + ";";
System.out.println("확인: " + sql);
int result = stmt.executeUpdate(sql);
return result;
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeStatement(stmt);
closeConnection(conn);
}
return 0;
}
// select문 - 테이블 보기
public static List<Book> selectAllBook() {
Connection conn = makeConnection();
Statement stmt = null;
ResultSet rs = null;
List<Book> list = new ArrayList<>();
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM book");
while (rs.next()) {
int no = rs.getInt("no");
String title = rs.getString("title");
int price = rs.getInt("price");
list.add(new Book(no, title, price));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeResultSet(rs);
closeStatement(stmt);
closeConnection(conn);
}
return list;
}
// 책 테이블에서 제목으로 검색하여 같은 이름의 책 모든 컬럼 값 콘솔에 출력하기
public static List<Book> selectBookByTitle(String t) {
Connection conn = makeConnection();
Statement stmt = null;
ResultSet rs = null;
List<Book> list = new ArrayList<>();
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM book WHERE title = '"+ t +"'");
while (rs.next()) {
int no = rs.getInt("no");
String title = rs.getString("title");
int price = rs.getInt("price");
list.add(new Book(no, title, price));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeResultSet(rs);
closeStatement(stmt);
closeConnection(conn);
}
return list;
}
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// 행추가
int result = insertBook(3, "올바름이라는착각", 14850);
System.out.println(result + "행 추가");
// 행삭제
int delete = deleteBook(2);
System.out.println(delete + "행 삭제");
// 행수정
int update = updateBook(1, "트렌드 코리아", 17100);
System.out.println(update + "행 수정");
// select문 - 테이블 보기
List<Book> books = selectAllBook();
System.out.println(books);
// 책 테이블에서 제목으로 검색하여 같은 이름의 책 모든 컬럼 값 콘솔에 출력하기
List<Book> books2 = selectBookByTitle("파워자바");
System.out.println(books2.size());
}
}
package dbutil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ConnectionProvider {
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection makeConnection() {
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/your_db", "root", "root");
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public static void closeConnection(Connection conn) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void closeStatement(Statement stmt) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void closeResultSet(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
연습 - Restaurant
public class Restaurant {
private int id;
private String name;
private String phoneNumber;
private String address;
private double score;
public Restaurant(String name, String phoneNumber, String address, double score) {
super();
this.name = name;
this.phoneNumber = phoneNumber;
this.address = address;
this.score = score;
}
public Restaurant(int id, String name, String phoneNumber, String address, double score) {
super();
this.id = id;
this.name = name;
this.phoneNumber = phoneNumber;
this.address = address;
this.score = score;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
@Override
public String toString() {
return "Restaurant [id=" + id + ", name=" + name + ", phoneNumber=" + phoneNumber + ", address=" + address
+ ", score=" + score + "]";
}
}
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import dbutil.ConnectionProvider;
public class RestaurantDB {
// 식당 행 추가하기 - 행개수 추가하기
public int create(String name, String phoneNumber, String address, double score) {
Connection conn = ConnectionProvider.makeConnection();
Statement stmt = null;
try {
stmt = conn.createStatement();
return stmt.executeUpdate("INSERT INTO Restaurant (name, phoneNumber, address, score)" + " VALUES ('" + name
+ "', '" + phoneNumber + "', '" + address + "', " + score + ")");
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionProvider.closeStatement(stmt);
ConnectionProvider.closeConnection(conn);
}
return 0;
}
public int create(Restaurant restaurant) {
return create(restaurant.getName(), restaurant.getPhoneNumber(), restaurant.getAddress(),
restaurant.getScore());
}
// 식당 행(pk로) 삭제하기
public int delete(int id) {
Connection conn = ConnectionProvider.makeConnection();
Statement stmt = null;
try {
stmt = conn.createStatement();
return stmt.executeUpdate("DELETE FROM restaurant WHERE id = " + id + ";");
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionProvider.closeStatement(stmt);
ConnectionProvider.closeConnection(conn);
}
return 0;
}
// 식당 행(pk로) 수정하기
public int update(int id, String name, String phoneNumber, String address, double score) {
Connection conn = ConnectionProvider.makeConnection();
Statement stmt = null;
try {
stmt = conn.createStatement();
return stmt.executeUpdate("UPDATE restaurant SET name = '" + name + "', phoneNumber = '" + phoneNumber
+ "', address = '" + address + "', score = " + score + " WHERE id = " + id + ";");
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionProvider.closeStatement(stmt);
ConnectionProvider.closeConnection(conn);
}
return 0;
}
public int update(int id, Restaurant restaurant) {
return update(id, restaurant.getName(), restaurant.getPhoneNumber(), restaurant.getAddress(),
restaurant.getScore());
}
// 식당 전부 다 조회하기
public List<Restaurant> selectAll() {
Connection conn = ConnectionProvider.makeConnection();
Statement stmt = null;
ResultSet rs = null;
List<Restaurant> list = new ArrayList<>();
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM restaurant;");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String phoneNumber = rs.getString("phoneNumber");
String address = rs.getString("address");
double score = rs.getDouble("score");
list.add(new Restaurant(id, name, phoneNumber, address, score));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionProvider.closeStatement(stmt);
ConnectionProvider.closeConnection(conn);
}
return list;
}
// 식당 이름으로 검색해서 조회하기
public List<Restaurant> selectByName(String n) {
Connection conn = ConnectionProvider.makeConnection();
Statement stmt = null;
ResultSet rs = null;
List<Restaurant> list = new ArrayList<>();
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM restaurant WHERE name = '" + n + "'");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String phoneNumber = rs.getString("phoneNumber");
String address = rs.getString("address");
double score = rs.getDouble("score");
list.add(new Restaurant(id, name, phoneNumber, address, score));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionProvider.closeResultSet(rs);
ConnectionProvider.closeStatement(stmt);
ConnectionProvider.closeConnection(conn);
}
return list;
}
// 집계 식당 총 몇 개?
public int countRestaurant() {
Connection conn = ConnectionProvider.makeConnection();
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT COUNT(*) FROM restaurant");
while (rs.next()) {
return rs.getInt("COUNT(*)");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionProvider.closeResultSet(rs);
ConnectionProvider.closeStatement(stmt);
ConnectionProvider.closeConnection(conn);
}
return 0;
}
// 점수 범위 X ~ Y 사이에 있는 식당 조회하기
public List<Restaurant> selectByScore(double start, double end) {
Connection conn = ConnectionProvider.makeConnection();
Statement stmt = null;
ResultSet rs = null;
List<Restaurant> list = new ArrayList<>();
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM restaurant " + "WHERE score BETWEEN " + start + " AND " + end
+ " ORDER BY score asc;");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String phoneNumber = rs.getString("phoneNumber");
String address = rs.getString("address");
double score = rs.getDouble("score");
list.add(new Restaurant(id, name, phoneNumber, address, score));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionProvider.closeResultSet(rs);
ConnectionProvider.closeStatement(stmt);
ConnectionProvider.closeConnection(conn);
}
return list;
}
// List<식당> 모든 원소 행 추가
public List<Restaurant> insertList(List<Restaurant> list) {
Iterator<Restaurant> e = list.iterator();
while (e.hasNext()) {
Restaurant r = e.next();
String name = r.getName();
String phoneNumber = r.getPhoneNumber();
String address = r.getAddress();
double score = r.getScore();
create(name, phoneNumber, address, score);
}
return selectAll();
}
}
import java.util.List;
public class Main {
public static void main(String[] args) {
RestaurantDB db = new RestaurantDB();
// 추가
int result = db.create("카오짜이", "000-4444", "중앙대로756", 5.0);
System.out.println(result + "행 추가");
result = db.create(new Restaurant("마마된장", "924-4008", "서면로68", 5.0));
System.out.println(result + "행 추가");
// 삭제
int result = db.delete(15);
System.out.println(result + "행 삭제");
// 수정
int result = db.update(12, "무무추", "444-5555", "부전시장", 4.0);
System.out.println(result + "행 수정");
// 조회
List<Restaurant> restaurants = db.selectAll();
System.out.println(restaurants);
// 이름검색
Restaurant r = db.selectByName("카오짜이");
System.out.println(r.toString());
// 식당 개수
System.out.println(db.countRestaurant());
// 점수범위 조회
System.out.println(db.selectByScore(4.0, 5.0));
// list추가
List<Restaurant> list = new ArrayList<>(Arrays.asList(
new Restaurant("보소보소", "456-7777", "부전동 999-4", 3.5)
, new Restaurant("버거킹", "666-6666", "부전동 111-4", 2.5)
));
List<Restaurant> result = db.insertList(list);
System.out.println(result);
}
}
DB 가져가기
Server > Data Export > Dump Structure and Data > Objects to Export 탭 모두 체크 > Export Options 탭 > Export to Self-Contained File 경로 선택 > Create Dump... , Include... 체크 > Start Export