JDBC(JAVA DataBase Connectivity)
: JAVA와 DataBase의 연동을 위한 프로그래밍 API
java.sql 패키지 안에 정의되어 있다
java프로그램에서 DB를 연동할 때 DBMS의 종류와 상관없이 통합적으로 처리하기 위해 만들어졌다
JDBC 프로그래밍 순서
1. JDBC 드라이버 로딩
2. 연결관리할 수 있는 객체 생성 : Connection
3. 쿼리 실행을 위한 객체 생성 : PreparedStatement
4. 쿼리 실행
5. 결과 사용 : select = ResultSet, insert delete update - int
6. ResultSet 종료
7. PreparedStatement 종료
8. Connection 종료
JDBC 드라이버 로딩
DBMS마다 별도의 드라이버가 필요하다
일반적으로 JAR파일 형태로 DBMS마다 기본적으로 제공한다
드라이버 위치
11G : C:\oraclexe\app\oracle\product\
18C : C:\app\Administrator\product\18.0.0\dbhomeXE\jdbc\lib
빌드패스를 통해 프로젝트에 추가
Class.forName("JDBC드라이버 클래스의 완전한 이름");
-> Class.forName("oracle.jdbc.OracleDriver")
* 주요 DBMS JDBC드라이버 클래스
oracle : oracle.jdbc.driver.OracleDriver ; 없애는 추세
: oracle.jdbc.OracleDriver
MySQL : com.mysql.jdbc.Driver
MS-SQL : com.microsoft.sqlserver.jdbc.SQLServerDriver
<JAVA Eclipse >
C:\app\Administrator\product\18.0.0\dbhomeXE\jdbc\lib
ojdbc8.jar 파일
쿼리 실행을 위한 객체 생성 : PreparedStatement
java.sql.Statement
정적 쿼리 방식
쿼리 실행마다 JVM에게 쿼리를 넘겨주어야 한다
넘어가는 데이터가 보여 보안에 문제가 있음
select * from testmember where name = ' + name + ';
java.sql.PreparedStatement ; 웹모듈 3.0 버전 이상부터 권장하는 방식
동적 쿼리 방식
객체 생성할 때 한번만 JVM에게 쿼리를 넘겨주면 된다
필요한 데이터를 JVM에게 넘겨주는 방식
select * from dbtest where name = ?
select * from dbtest where name = '김땡땡';
-> 속도적인 측면에서 더 빠르다
쿼리 실행을 위한 메소드
boolean execute () -X
ResultSet 타입이면 True 아니면 False를 반환
long executeLargeUpdate () -X
insert, delete, update
대량의 데이터를 이용할 때 사용
int executeUpdate ()
insert, delete, update문에서 실행 결과를 받을 때 사용하는 메소드
ResultSet executeQuery ()
select문에서 실행 결과를 받을 때 사용하는 메소드
Interface Statement
execute (String sql)
excuteLargeUpdate (String sql)
executeQuery (String sql)
excuteUpdate (String sql)
Interface PreparedStatement
execute ()
excuteLargeUpdate ()
executeQuery ()
excuteUpdate ()
=>
package jdbc;
public class Test01 {
public static void main(String[] args) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("로딩 성공"); // 연결 여부를 눈으로 확인하기 위해 사용
} catch (ClassNotFoundException e) {
System.err.println("로딩 실패");
e.printStackTrace();
}
}
}
출력화면
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
// connection 객체 생성
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String user = "c##jsp01";
String password = "oracle";
Connection con = null;
try {
con = DriverManager.getConnection(url, user, password);
System.out.println("연결 성공!");
} catch (SQLException e) {
System.out.println("연결 실패");
}
출력화면
// 데이터 입력 받기
Scanner sc = new Scanner(System.in);
System.out.print("이름 입력 : ");
String name = sc.next();
System.out.print("나이 입력 : ");
int age = sc.nextInt();
System.out.print("키 입력 : ");
double height = sc.nextDouble();
sc.close();
// Statement
Statement stmt = null;
String sql = "insert into dbtest values('" + name + "'," + age + ", " + height + ", sysdate)";
System.out.println(sql);
try {
stmt = con.createStatement();
int su = stmt.executeUpdate(sql);
if(su !=0) {
System.out.println(name + "님의 정보가 추가되었습니다.");
} else {
System.out.println("정보 입력에 실패하였습니다.");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) {
stmt.close();
}
if (con !=null) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
출력화면
// PreparedStatement
PreparedStatement ps = null;
String sql = "insert into dbtest values(?, ?, ?, sysdate)";
System.out.println(sql);
try {
ps = con.prepareStatement(sql);
ps.setString(1, name);
ps.setInt(2, age);
ps.setDouble(3, height);
int su = ps.executeUpdate();
if(su !=0) {
System.out.println(name + "님의 정보가 추가되었습니다.");
} else {
System.out.println("정보 입력에 실패하였습니다.");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (ps != null) {
ps.close();
}
if (con !=null) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
출력화면
Exercise 1
이름을 기준으로 키와 나이 수정
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class Test02 {
public static void main(String[] args) {
try {
String path = "java.lang.String";
try {
String str = (String) Class.forName(path).newInstance();
System.out.println(str.getClass());
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
Class.forName("oracle.jdbc.OracleDriver");
System.out.println("로딩 성공!");
} catch (ClassNotFoundException e) {
System.out.println("로딩 실패!");
e.printStackTrace();
}
// Connection 객체 생성
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String user = "c##jsp01";
String password = "oracle";
Connection con = null;
try {
con = DriverManager.getConnection(url, user, password);
System.out.println("연결 성공!");
} catch (SQLException e) {
System.out.println("연결 실패");
}
Scanner sc = new Scanner(System.in);
System.out.print("이름 입력 : ");
String name = sc.next();
System.out.print("나이 입력 : ");
int age = sc.nextInt();
System.out.print("키 입력 : ");
double height = sc.nextDouble();
sc.close();
// Statement
Statement stmt = null;
String sql = String.format("update dbtest set age=%d, height=%f where name='%s'", age, height, name);
System.out.println(sql);
try {
stmt = con.createStatement();
int su = stmt.executeUpdate(sql);
if(su !=0) {
System.out.println(name + "님의 정보가 수정되었습니다.");
} else {
System.out.println("정보 수정에 실패하였습니다.");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) {
stmt.close();
}
if (con !=null) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
// 또는 PreparedStatement로 실행
PreparedStatement ps = null;
String sql = "update dbtest set age=?, height=? where name=?";
System.out.println(sql);
try {
ps = con.prepareStatement(sql);
ps.setString(3, name);
ps.setInt(1, age);
ps.setDouble(2, height);
int su = ps.executeUpdate();
if(su !=0) {
System.out.println(name + "님의 정보가 수정되었습니다.");
} else {
System.out.println("정보 수정에 실패하였습니다.");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (ps != null) {
ps.close();
}
if (con !=null) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
출력화면
JAVA Eclipse에서 JDBC SQL연동해서 Statement로 DataBase 입력, 수정하기
'DB > JDBC' 카테고리의 다른 글
JDBC(JAVA DataBase Connectivity) JAVA Eclipse SQL (0) | 2023.04.25 |
---|