JAVA 기반 애플리케이션의 데이터를 데이터베이스에 저장 및 업데이트하거나, 데이터베이스에 저장된 데이터를 JAVA에서 사용할 수 있도록 하는 자바 API





자바프로젝트 안에 JDBC Driver가 있을 경우
-> Libraries > Classpath > Add JARs > JDBC Driver가 있는 자바프로젝트에서 가져오기
다운로드 받은 JDBC Driver를 가져올 경우
-> Libraries > Classpath > Add External JARs > JDBC Driver가 있는 폴더 내에서 가져오기
Class.forName("oracle.jdbc.OracleDriver");
DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521/모델명"
"scott" // 아이디
"1004" // 비밀번호
);
Class.forName("org.mariadb.jdbc.Driver");
DriverManager.getConnection(
"jdbc:mariadb://localhost:3306/모델명"
"scott" // 아이디
"1004" // 비밀번호
);
package ch20.oracle.sec05;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ConnectionExample {
public static void main(String[] args) {
Connection conn = null;
try {
//JDBC Driver 등록
//이 파일이 없으면 sql구문 작업 자체가 안됨;
// Oracle Driver 등록
Class.forName("oracle.jdbc.OracleDriver");
// mariaDB Driver 등록
//Class.forName("org.mariadb.jdbc.Driver");
//연결하기
conn = DriverManager.getConnection(
// 연결 정보를 전달함
// 로컬호스트 뒤에 oracle DB명을 명시하기
"jdbc:oracle:thin:@localhost:1521/xe",
// oracle db를 이용해 다른 사람의 데이터베이스를 불러올 수 있음
//"jdbc:oracle:thin:@192.168.4.44:1521/xe",
// mariaDB의 연결 정보를 전달
//"jdbc:mariadb://localhost:3306/kosa_db",
// 아이디
"scott",
// 비번
"1004"
);
// SQL 구문 생성
Statement stmt = conn.createStatement();
// select 구문 실행
ResultSet rs = stmt.executeQuery("SELECT * FROM accounts");
// SQL 구문 객체 생성
Statement insertStmt = conn.createStatement();
// insert 구문 실행
insertStmt.execute("INSERT INTO accounts (ano, OWNER, balance) VALUES (lpad(seq_ano.nextval,12,'0'), '이동주', 50000)");
ResultSet rs1 = stmt.executeQuery("SELECT * FROM accounts");
while(rs1.next()) {
// select문 읽어들이기 : 열의 번호
System.out.println(rs1.getString(1) + " : " + rs1.getString(2) + " : " + rs1.getString(3));
// select문 읽어들이기 : 컬럼명
System.out.println(rs1.getString("ANO") + " : " + rs1.getString("owner") + " : " + rs1.getString("balance"));
}
rs.close();
stmt.close();
System.out.println("연결 성공");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
}
finally {
if(conn != null) {
try {
//연결 끊기
conn.close();
System.out.println("연결 끊기");
} catch (SQLException e) {}
}
}
}
}
package ch20.oracle.sec05;
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 BoardConnection {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
while(true) {
select(selectMenu());
}
}
private static void list() {
Connection conn = null;
try {
//JDBC Driver 등록
Class.forName("oracle.jdbc.OracleDriver");
System.out.println("드라이버 로딩 ");
// 연결하기 : Oracle JDBC 연결
conn = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521/XE",
// 아이디
"scott",
// 비번
"1004"
);
//SQL 구문 객체 생성한다
Statement stmt = conn.createStatement();
//select 구문을 실행한다
// select 구문을 실행할 때에는 executeQuery 메소드 사용
ResultSet rs = stmt.executeQuery("SELECT * FROM boards");
// 결과 집합을 하나씩 읽어옴
while(rs.next()) {
// 칼럼 이름으로 결과값을 호출함
System.out.println(rs.getString("bno") + " : " + rs.getString("btitle") + " : " + rs.getString("bcontent")
+ " : " + rs.getString("bwriter") + " : " + rs.getString("bdate"));
}
// 구문 닫기
rs.close();
// SQL 구문 종료
stmt.close();
System.out.println("연결 성공");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if(conn != null) {
try {
//연결 끊기
conn.close();
System.out.println("연결 끊기");
} catch (SQLException e) {}
}
}
}
private static String selectMenu() {
System.out.println("1. 게시글목록");
System.out.println("2. 게시글등록");
System.out.println("3. 게시글수정");
System.out.println("4. 게시글삭제");
System.out.println("5. 종료");
System.out.print("원하는 작업은 ?");
return scanner.nextLine();
}
private static void select(String select) {
switch(select) {
case "1": list(); break;
case "2": insert(); break;
case "3": update(); break;
case "4": delete(); break;
case "5":
System.out.println("프로그램 종료");
System.exit(0);
break;
default: System.out.println("입력이 잘못되었습니다");
}
}
private static void insert() {
Connection conn = null;
try {
//JDBC Driver 등록
Class.forName("oracle.jdbc.OracleDriver");
System.out.println("드라이버 로딩 ");
// //연결하기
conn = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521/XE",
"scott",
"1004"
);
//SQL 구문 객체 생성한다
Statement insertStmt = conn.createStatement();
String title;
String content;
String writer;
System.out.print("제목 : ");
title = scanner.nextLine();
System.out.print("내용 : ");
content = scanner.nextLine();
System.out.print("작성자 : ");
writer = scanner.nextLine();
//insert 구문 실행
//insert, update, delete 구문은 execute를 사용하여 구문을 불러옴
insertStmt.execute(
"INSERT INTO boards (bno, btitle, bcontent, bwriter, bdate) VALUES (to_number(lpad(SEQ_BNO.nextval,4,'0')), '"
+ title + "', '" + content + "', '" + writer +"', sysdate)");
insertStmt.close();
System.out.println("연결 성공");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if(conn != null) {
try {
//연결 끊기
conn.close();
System.out.println("연결 끊기");
} catch (SQLException e) {}
}
}
}
private static void update() {
Connection conn = null;
try {
//JDBC Driver 등록
Class.forName("oracle.jdbc.OracleDriver");
System.out.println("드라이버 로딩 ");
// //연결하기
conn = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521/XE",
"scott",
"1004"
);
//SQL 구문 객체 생성한다
Statement updateStmt = conn.createStatement();
String title;
String newContent;
System.out.print("수정할 글 제목 : ");
title = scanner.nextLine();
System.out.print("글 내용 수정 : ");
newContent = scanner.nextLine();
//update 구문 실행
//insert, update, delete 구문은 execute를 사용하여 구문을 불러옴
updateStmt.execute("UPDATE BOARDS"
+ " SET bcontent = '" + newContent + "',"
+ " bdate = sysdate"
+ " WHERE btitle = '"+ title +"'");
updateStmt.close();
System.out.println("연결 성공");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if(conn != null) {
try {
//연결 끊기
conn.close();
System.out.println("연결 끊기");
} catch (SQLException e) {}
}
}
}
private static void delete() {
Connection conn = null;
try {
//JDBC Driver 등록
Class.forName("oracle.jdbc.OracleDriver");
System.out.println("드라이버 로딩 ");
// //연결하기
conn = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521/XE",
"scott",
"1004"
);
//SQL 구문 객체 생성한다
Statement deleteStmt = conn.createStatement();
String title;
System.out.print("삭제할 글 제목 : ");
title = scanner.nextLine();
//delete 구문 실행
//insert, update, delete 구문은 execute를 사용하여 구문을 불러옴
deleteStmt.execute("delete from boards WHERE btitle = '" + title + "'");
deleteStmt.close();
System.out.println("연결 성공");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if(conn != null) {
try {
//연결 끊기
conn.close();
System.out.println("연결 끊기");
} catch (SQLException e) {}
}
}
}
}
// SQL 구문 객체 생성
// 입력받을 값에 ?로 처리함
PreparedStatement insertStmt = conn.prepareStatement(
"insert into 테이블명 (칼럼1, 칼럼2, ..., 칼럼n)
values (?, ?, ..., ?)");
// insert/update/delete문에 해당 칼럼에 값 집어넣기
insertStmt.setString(인덱스번호 (?의 위치번호), 값);
// SQL문 실행 및 값 저장
insertStmt.excute();
// PreparedStatement가 사용했던 메모리 해제 (SQL문 닫기)
insertStmt.close();
ResultSet : select문에 기술된 컬럼으로 구성된 행(row)의 집합
executeQuery() : select문을 호출하는 메소드로, 해당 메소드로 가져온 데이터를 ResultSet에 저장하고 리턴함
ResultSet 구조

ResultSet은 커서가 있는 행의 데이터만 읽기 때문에 첫 행을 읽기 위해서는 next() 메소드로 커서를 이동해야 함!
ResultSet rs = pstmt.executeQuery();
if(rs.next()) {
// 첫 번째 데이터 행 처리
} else {
// 이후 데이터 행 처리
}
ResultSet rs = pstmt.executeQuery();
while(rs.next()) {
// 마지막 행까지 이동하면서 데이터 행 처리
}
// 마지막 행 다음으로 커서를 이동했을 경우
String 칼럼명1 = rs.getString("칼럼명1");
String 칼럼명2 = rs.getString("칼럼명2");
int 칼럼명3 = rs.getInt("칼럼명3");
String 칼럼명1 = rs.getString(1);
String 칼럼명2 = rs.getString(2);
int 칼럼명3 = rs.getInt(3);
일반 쿼리문

저장 프로시저


