BookDB 구조

> SQL구문
create database bookdb;
use bookdb;
create table book(
id int(11) not null primary key,
title varchar(50) not null,
publisher varchar(30) not null,
author varchar(30) not null );
commit;
자바와 MySQL 연결문
sql을 불러와 사용할 경우 sql 관련 패키지를 import 해야 합니다.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
sql과 연동을 해줄 connection 객체와 데이터 베이스의 현재 상태를 의미하는 Statement 객체를 생성합니다.
static Connection conn; //sql과 연결하기 위한 Connection
static Statement stmt = null; //현 상태를 알려주는 statement
try-catch 구문을 이용하여 Mysql에 접근하고, 발생 가능한 오류를 catch 해주면, 자바에서 SQL을 사용할 환경이 완성됩니다!!
try {
//연결 경로-sql workbench-비밀번호 입력
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/bookdb";
String userName = "root";
String password = "gging00100!";
conn = DriverManager.getConnection(url, userName, password);
System.out.println("DB 연결 완료");
stmt = conn.createStatement(); // SQL문 처리용 Statement 객체 생성
printTable(stmt); // 모든 데이터 출력
} catch (ClassNotFoundException e) {
System.out.println("JDBC 드라이버 로드 에러");
} catch (SQLException e) {
System.out.println("SQL 실행 에러");
}
마지막으로, 현재의 데이터 베이스 상태를 출력하는 PrintTable 함수를 만들어 주었습니다.
// 레코드의 각 열의 값 화면에 출력
private static void printTable(Statement stmt) {
ResultSet srs;
System.out.printf("%4s |%-29s|%-28s|%-10s\n", "ID","제목", "출판사", "작가");
System.out.println("-----------------------------------------------------------------------------------");
try {
srs = stmt.executeQuery("select * from book");
while (srs.next()) {
System.out.printf("%4s |%-30s|%-30s|%-10s\n", new String(srs.getString("id")), srs.getString("title"), srs.getString("publisher"), srs.getString("author"));
}
} catch (SQLException e) {
System.out.println("SQL 실행 에러");
}
}
키보드 입력 받기
키보드 입력을 받아오기 위해 Scanner 객체를 생성하고,
추가, 삭제, 수정, 프로그램 종료를 선택 받아 실행하도록 구조를 만들어 줍니다.
static Scanner sin = new Scanner(System.in); //사용자 입력을 받기 위한 스캐너
int choice = 1;
while (choice != 4) {
System.out.println();
System.out.print("추가(1),삭제(2), 수정(3), 끝내기(4)>>");
choice = Integer.parseInt(sin.nextLine());
switch (choice) {
case 1:
add();
break;
case 2:
delete();
break;
case 3:
update();
break;
case 4:
System.out.println("프로그램 종료~!");
break;
default:
System.out.println("잘못 입력하셨습니다.");
}
}
이제 각각의 함수들의 내용을 살펴 봅시다~
데이터 추가 함수
"+ id +",'" + title + "','" + publisher + "','" + author + "'
##유의할 점 : 사용자 입력을 받아와 SQL구문을 사용할 때는" + 변수 + " 형식으로 입력해 주어야 합니다.
이 때, 변수가 문자열이라면 ' " + 변수 + " ' 형식으로 작은 따옴표 속에 한번 더 넣어 줍니다.
private static void add() {
try {
System.out.print("id>>");
int id = Integer.parseInt(sin.nextLine());
System.out.print("책 이름>>");
String title = sin.nextLine();
System.out.print("출판사>>");
String publisher = sin.nextLine();
System.out.print("작가>>");
String author = sin.nextLine();
stmt.executeUpdate("insert into book (id, title, publisher, author) values("+ id +",'" + title + "','" + publisher + "','" + author + "');"); // 레코드 추가
printTable(stmt);
} catch (SQLException e) {
System.out.println("레코드 추가 에러");
}
}
데이터 수정 함수
private static void update() {
try {
System.out.print("수정할 속성 이름>>");
String colName = sin.nextLine();
System.out.print("수정할 속성의 현재값 >>");
String oldValue = sin.nextLine();
System.out.print("수정할 속성의 새로운 값 >>");
String newValue = sin.nextLine();
if (colName.equals("id"))
stmt.executeUpdate("update book set " + colName + "="+ newValue + " where " + colName + "="+ oldValue + ""); //데이터 수정
else
stmt.executeUpdate("update book set " + colName + "='"+ newValue + "' where " + colName + "='"+ oldValue +"'"); //데이터 수정
printTable(stmt);
} catch (SQLException e) {
System.out.println("레코드 수정 에러");
}
}
데이터 삭제 함수
private static void delete() {
try {
System.out.print("id>>");
int id = Integer.parseInt(sin.nextLine());
stmt.executeUpdate("delete from book where id="+id); // 레코드 삭제
printTable(stmt);
} catch (SQLException e) {
System.out.println("레코드 삭제 에러");
}
}
Book Management Program
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class BookDBManager {
static Connection conn;
static Statement stmt = null;
static Scanner sin = new Scanner(System.in);
public static void main (String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/bookdb";
String userName = "root";
String password = "비밀";
conn = DriverManager.getConnection(url, userName, password);
System.out.println("DB 연결 완료");
stmt = conn.createStatement(); // SQL문 처리용 Statement 객체 생성
printTable(stmt); // 모든 데이터 출력
int choice = 1;
while (choice != 4) {
System.out.println();
System.out.print("추가(1),삭제(2), 수정(3), 끝내기(4)>>");
choice = Integer.parseInt(sin.nextLine());
switch (choice) {
case 1:
add();
break;
case 2:
delete();
break;
case 3:
update();
break;
case 4:
System.out.println("프로그램 종료~!");
break;
default:
System.out.println("잘못 입력하셨습니다.");
}
}
} catch (ClassNotFoundException e) {
System.out.println("JDBC 드라이버 로드 에러");
} catch (SQLException e) {
System.out.println("SQL 실행 에러");
}
}
private static void update() {
try {
System.out.print("수정할 속성 이름>>");
String colName = sin.nextLine();
System.out.print("수정할 속성의 현재값 >>");
String oldValue = sin.nextLine();
System.out.print("수정할 속성의 새로운 값 >>");
String newValue = sin.nextLine();
if (colName.equals("id"))
stmt.executeUpdate("update book set " + colName + "="+ newValue + " where " + colName + "="+ oldValue + ""); //데이터 수정
else
stmt.executeUpdate("update book set " + colName + "='"+ newValue + "' where " + colName + "='"+ oldValue +"'"); //데이터 수정
printTable(stmt);
} catch (SQLException e) {
System.out.println("레코드 수정 에러");
}
}
private static void delete() {
try {
System.out.print("id>>");
int id = Integer.parseInt(sin.nextLine());
stmt.executeUpdate("delete from book where id="+id); // 레코드 삭제
printTable(stmt);
} catch (SQLException e) {
System.out.println("레코드 삭제 에러");
}
}
private static void add() {
try {
System.out.print("id>>");
int id = Integer.parseInt(sin.nextLine());
System.out.print("책 이름>>");
String title = sin.nextLine();
System.out.print("출판사>>");
String publisher = sin.nextLine();
System.out.print("작가>>");
String author = sin.nextLine();
stmt.executeUpdate("insert into book (id, title, publisher, author) values("+ id +",'" + title + "','" + publisher + "','" + author + "');"); // 레코드 추가
printTable(stmt);
} catch (SQLException e) {
System.out.println("레코드 추가 에러");
}
}
// 레코드의 각 열의 값 화면에 출력
private static void printTable(Statement stmt) {
ResultSet srs;
System.out.printf("%4s |%-29s|%-28s|%-10s\n", "ID","제목", "출판사", "작가");
System.out.println("-----------------------------------------------------------------------------------");
try {
srs = stmt.executeQuery("select * from book");
while (srs.next()) {
System.out.printf("%4s |%-30s|%-30s|%-10s\n", new String(srs.getString("id")), srs.getString("title"), srs.getString("publisher"), srs.getString("author"));
}
} catch (SQLException e) {
System.out.println("SQL 실행 에러");
}
}
}
반응형