- Application1
package jdbc;
import java.sql.*;
public class Application {
public static void main(String[] args) throws ClassNotFoundException {
//1.jvm에 클래스 로드
Class.forName("oracle.jdbc.driver.OracleDriver");
//2.드라이버 매니저로부터 커넥션 얻어옴
try ( final Connection conn =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE",
"system", "oracle"
);
//3.데이터베이스 작업
PreparedStatement pstmt =
conn.prepareStatement("SELECT 1 FROM dual");
)
{
final ResultSet rs = //쿼리결과를 담는
pstmt.executeQuery(); //쿼리를 실행
rs.next();
int value = rs.getInt(1);
System.out.println(value);
} catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
SELECT 1 FROM dual 이라는 sql문을 만들기
ResultSet이라는 곳에 담아서 출력
- Application2
package jdbc;
import java.sql.*;
public class Application2 {
public static void main(String[] args) throws ClassNotFoundException {
//1.jvm클래스 로드
Class.forName("oracle.jdbc.driver.OracleDriver");
try
(final Connection conn =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE",
"system", "oracle"
);
){
final String name = "abc";
final String email = "a@b.com";
final String sql = "INSERT INTO jdbc_example VALUES(seq_jdbc_example_pk.nextval, ?, DEFAULT, ?)";
final PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setString(2, email);
final int affectedRows = pstmt.executeUpdate();
System.out.println(affectedRows);
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
INSERT INTO jdbc_example VALUES(seq_jdbc_example_pk.nextval, ?, DEFAULT, ?)이라는 sql문
pstmt.setString(1, name); //1은 첫번쨰 물음표를 name으로
pstmt.setString(2, email); //2는 두번째 물음표를 email로
- Application3
package jdbc;
import java.sql.*;
import java.time.LocalDateTime;
public class Application3 {
public static void main(String[] args) throws ClassNotFoundException {
//1.jvm클래스 로드
Class.forName("oracle.jdbc.driver.OracleDriver");
try
(final Connection conn =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE",
"system", "oracle"
);
){
final String sql = "SELECT * FROM jdbc_example ";
final PreparedStatement pstmt = conn.prepareStatement(sql);
final ResultSet rs = pstmt.executeQuery();
rs.next();
// final int id = rs.getInt("id");
// final String name = rs.getString("name");
// final LocalDateTime localDateTime = rs.getTimestamp("time").toLocalDateTime();
// final String email = rs.getString("email");
while(rs.next()) {
final int id = rs.getInt("id");
final String name = rs.getString("name");
final LocalDateTime localDateTime = rs.getTimestamp("time").toLocalDateTime();
final String email = rs.getString("email");
System.out.println(id);
System.out.println(name);
System.out.println(localDateTime);
System.out.println(email);
System.out.println("---------------");
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
하나만꺼내고싶으면 sql문에 where id = 2이런식으로 지정.
id, name등의 변수를 만들어 rs.getInt("id)의 값을 담아줌
rs.next()의 뜻은 다음에 행이 있으면 실행하고 없으면 실행하지 않는다는 뜻
- Application4
package jdbc;
import java.sql.*;
import java.time.LocalDateTime;
import java.util.*;
public class Application4 {
private static final String JDBC_URL = "jdbc:oracle:thin:@localhost:1521:XE";
private static final String DB_USER = "system";
private static final String DB_PASS = "oracle";
public static void main(String[] args) throws ClassNotFoundException {
//1.jvm클래스 로드
Class.forName("oracle.jdbc.driver.OracleDriver");
try
(final Connection conn =
DriverManager.getConnection(JDBC_URL,DB_USER,DB_PASS )){
String sql = "SELECT * FROM jdbc_example";
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
List<JdbcExample> list = new ArrayList<>();
while(rs.next()) {
JdbcExample jdbcExample = read(rs);
list.add(jdbcExample);
}
for (JdbcExample jdbcExample : list) {
System.out.println(jdbcExample);
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
private static JdbcExample read(ResultSet rs) throws SQLException {
long id = rs.getLong("id");
String name = rs.getString("name");
LocalDateTime time = rs.getTimestamp("time").toLocalDateTime();
String email = rs.getString("email");
return new JdbcExample(id, name, time, email);
}
}
주소나 username 비번등이 너무 기니까 변수에 담아 짧게 바꿔줌
SELECT * FROM jdbc_example이라는 쿼리를 pstmt에 담아 결과값을 ResultSet에 담아둠
JdbcExample이라는 클래스를 만들어 ArrayList의 꺽새안에 넣어줌
while문활용하여 읽은 값들을 jdbcExample이라는 곳에 저장하고
for-each문을 통해 출력
read라는 메소드를 따로 만들어줌 (위에서 깔끔하게 정리했던 부분)
- JdbcExample
package jdbc;
import java.time.LocalDateTime;
public class JdbcExample {
private long id;
private String name;
private LocalDateTime time;
private String eamil;
public JdbcExample(long id, String name, LocalDateTime time, String eamil) {
this.id = id;
this.name = name;
this.time = time;
this.eamil = eamil;
}
@Override
public String toString() {
return "JdbcExample [id=" + id + ", name=" + name + ", time=" + time + ", eamil=" + eamil + "]";
}
}
source-generate constructor using fields를 통해 값 네개를 읽어 저장하는 생성자만들어주고
source-tostring어쩌고를 통해 tostring메소드 자동생성
- Application5
package kr.or.iei;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Application5 {
private static final String JDBC_URL = "jdbc:oracle:thin:@localhost:1521:XE";
private static final String DB_USER = "system";
private static final String DB_PASS = "oracle";
public static void main(String[] args) throws ClassNotFoundException {
// 1. 클래스 로드
Class.forName("oracle.jdbc.driver.OracleDriver");
// 2. 데이터베이스에 접속
try (final Connection conn = DriverManager.getConnection(JDBC_URL, DB_USER, DB_PASS)) {
final String sql = "UPDATE jdbc_example SET name = ? WHERE 1 = 1";
// 3. 데이터베이스 작업
final PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "java");
final int affectedRows = pstmt.executeUpdate();
System.out.println(affectedRows);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
UPDATE 테이블이름 SET 바꿀값
여기서 WHERE 1 = 1 은 항상 참이니까 모든값을 바꿔준다
- Application6
package jdbc;
import java.sql.*;
import java.time.LocalDateTime;
import java.util.*;
public class Application6{
private static final String JDBC_URL = "jdbc:oracle:thin:@localhost:1521:XE";
private static final String DB_USER = "system";
private static final String DB_PASS = "oracle";
public static void main(String[] args) throws ClassNotFoundException {
//1.jvm클래스 로드
Class.forName("oracle.jdbc.driver.OracleDriver");
try
(final Connection conn =
DriverManager.getConnection(JDBC_URL,DB_USER,DB_PASS )){
final String sql = "DELETE FROM jdbc_example";
PreparedStatement pstmt = conn.prepareStatement(sql);
int affectedRows = pstmt.executeUpdate();
System.out.println(affectedRows);
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
5랑다른점은 쿼리문만 바뀐것
DELETE구문임
DELETE FROM 테이블이름
- SQL문
DROP TABLE jdbc_example CASCADE CONSTRAINTS;
CREATE TABLE jdbc_example(
id NUMBER PRIMARY KEY,
name VARCHAR2(128) NOT NULL ,
time TIMESTAMP DEFAULT sysdate
);
DROP SEQUENCE seq_jdbc_example_pk;
CREATE SEQUENCE seq_jdbc_example_pk;
INSERT INTO jdbc_example VALUES(seq_jdbc_example_pk.nextval, 'chwon', DEFAULT);
ALTER TABLE jdbc_example add email VARCHAR2(128);
SELECT * FROM jdbc_example;
쉬워서 넘겼었는데 ALTER TABLE부분이 좀 헷갈렸다 ...
시퀀스가 뭔지 헷갈렸는데 그냥 인덱스처럼 하나씩 늘어나는 거였다
- 시퀀스 생성문 참고
CREATE SEQUENCE seq_product_no
START WITH 1
INCREMENT BY 1
MAXVALUE 10000
NOCYCLE;
CREATE SEQUENCE 시퀀스네임
START WITH 시작점
INCREMENT BY 증가값
MAXVALUE 최댓값
NOCYCLE 반복x
이지만
'CREATE SEQUENCE 시퀀스이름' 만 써도 기본값으로 실행이된다
'JAVA > Java' 카테고리의 다른 글
20201104_28 thread (0) | 2020.11.04 |
---|---|
20201104_28 jdbc (0) | 2020.11.04 |
20201103_27 A와 B 돈인출, review (0) | 2020.11.03 |
20201103_27 JVM (0) | 2020.11.03 |
20201030_25 이진법, 상속, 클래스 등 (0) | 2020.10.30 |
댓글