Mon/Jan/13 [Java] Day10. Exception 예외처리, Java-SQL 연결과 기본문법
Mon/Jan/13
[Java]
Day10. 예외처리, SQL연결
자바 내부 코드와 외부데이터 사이 input/output 할 경우 <반드시> 예외처리
실행도중 문제가 발생할 경우 프로그램이 강제 종료되는 것 방지
예외처리가 필요한 경우
- DB 연결
- 외부 파일 연결
- Internet 연결 : Java web
- thread
예외처리 기본 문법
1
2
3
4
5
|
try{
(문제 발생 예상 코드)
} catch(예외가 발생할 경우 문제점을 제시해주는 class를 parameter e로 지정) {
System.out.print(e.getMessage());
}
| cs |
Exception.class - 모든 예외처리 class의 조상
세부적인 내용은 알려주지 못함
* method 선언시 예외처리
1
2
3
4
5
6
7
8
|
// method 내부에 예외처리를 하는 경우
methodName (**) throws className{
.....
try{}
catch() {}
}
// method 외부에서 예외처리하는 경우는 호출시에도 예외처리해줘야 ?
| cs |
* 외부data 없는 코드에서 try/catch 있는 경우 = 오류
외부data 있는 코드에서 try/catch 없는 경우 = 오류
* Java와 DB를 연결에 data 파일 만들어 외부 저장하고 인터넷에 올리는 경우
⇒ 예외처리가 3번 필요
⇒ try 하나로 세번 catch 묶어서 보기 편하게 처리
1
2
3
4
5
6
7
8
9
|
try{
}catch(){
}catch(){
}catch(){
}
| cs |
1
2
3
4
5
6
7
|
try{
// 예외 발생예상 코드
}catch(){
// 문제점 해결 코드
}finally(){
// 자원 해제 method == .close()
}
| cs |
<File>
1. File.class 를 통해 file 다루기
new File("경로")
| cs |
import java.io.File;
public class MainClass {
public static void main(String[] args) {
File f = new File("c:/filetest");
System.out.println("읽을 수 있는지? "+ f.canRead());
System.out.println("쓸 수 있는지? " + f.canWrite());
System.out.println("폴더인지? " + f.isDirectory());
System.out.println("파일인지? " + f.isFile());
System.out.println("마지막 수정일 10진수로? " + f.lastModified());
// 1970.1.1. 00:00 기준 현재까지의 시간
System.out.println("파일의 크기? " + f.length());
// byte
System.out.println("폴더일 경우 내부 폴더 및 파일 이름들 " + f.list());
// 배열의 번지값 String으로 return
// System.out.println(file_list[i]); 로 String Array 출력 가능
}
}
| cs |
String uri = "c:/windows/";
File f = new File(uri);
System.out.println("파일 크기 : " + f.length());
System.out.println("\n파일과 폴더 구분해서 출력");
String[] fileList = f.list();
for(int i=0; i<fileList.length; i++){
File f2 = new File(uri + fileList[i]);
if(f2.isDirectory()){
System.out.println("폴더 : " + fileList[i]);
} else if (f2.isFile()){
System.out.println("파일 : " + fileList[i]);
}
}
| cs |
★ 수시로 쓰이는 코드이므로, 반드시 잘 기억해두자 ★
2. file 내부 text data 읽기
- 글자 1개씩 byte 단위로 읽는 방법 > char로 형 변환; 잘 안씀
read(); // method of FileReader, (char) byte
| cs |
- 한 줄 씩 읽는 방법
readLine();
// method of BufferedReader, (String) , 주로 쓰는 type, BUT 파일을 읽지는 못함, FileReader 필요한 이유
//1. FileReader 객체 생성; 경로 및 파일 불러오기
new FileReader("");
// 2. BufferedReader 객체 생성;; parameter = Object of FileReader
new BufferedReader(FileReader 객체);
| cs |
* about FileReader.class
- super class == File.class
- local files 다룰 때
* ~~InputStream.class : network를 통해 data를 읽을 때
Stream은 binary를 의미
반대로 ~~OutputStream은 network 통해 data 내보낼 때
import java.io.FileReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
public static void main(String[] args) {
// 1. FileReader 객체 생성; 경로 및 파일 불러오기
FileReader fr;
try {
fr = new FileReader("c:/filetest/memo.txt"); // 실제 file 읽어옴
// 2. BufferedReader 객체 생성;; parameter = Object of FileReader
BufferedReader br = new BufferedReader(fr); // fr이 가져온 text를 줄단위로 읽음
System.out.println(br.readLine()); // 맨 위부터 한줄씩 text 가져오기, 읽을 떄도 예외처리 필요 > IOExeption
System.out.println(br.readLine());
System.out.println(br.readLine());
System.out.println(br.readLine());
} catch (IOException fnfe) {
// 매개변수 이름은 앞 클래스의 대문자만 따서 만드는 것이 관례
// FileNotFoundException 예외처리 : file이 존재하지 않을 때
// br.readLine() 예외처리로 조상인 IOException 생기면서 삭제
System.out.println(fnfe.getMessage());
// e.printStackTrace(); 별로 의미 없는 코드, error 메시지가 뜨지 않음
}
}
| cs |
import java.io.FileReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
public class MainClass {
public static void main(String[] args) {
// 1. FileReader 객체 생성; 경로 및 파일 불러오기
FileReader fr;
try {
fr = new FileReader("c:/filetest/memo.txt"); // 실제 file 읽어옴
// 2. BufferedReader 객체 생성;; parameter = Object of FileReader
BufferedReader br = new BufferedReader(fr); // fr이 가져온 text를 줄단위로 읽음
// 전체 text 긁어오기
String line = ""; // 초기값 지정
while (true) {
line = br.readLine();
if(line==null){ // EOF : End of File (문서의 끝) 나올 때까지 무한loop
break;
}
System.out.println(line);
}
} catch (IOException fnfe) {
System.out.println(fnfe.getMessage());
}
}
}
| cs |
* 위 while loop 깔끔하게 만들기 ★ 자주 쓰이는 코드 ★
while ((line = br.readLine()) != null) {
System.out.println(line);
}
| cs |
3. 파일에 data 쓰기
- 한 줄씩 쓰기
- FileWriter.class : 실제로 글을 쓰는 역할, write("문자열")
- BufferedWriter.class : newLine() / write("문자열")
- 어느 경로에 어떤 파일명으로 저장할 것인지?
package com.wjh.lessons;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class MainClass {
public static void main(String[] args) {
String uri = "c:/filetest/test.txt";
try {
FileWriter fw = new FileWriter(uri);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("지금부터 test.txt 파일에 글을 적습니다.");
bw.newLine();
bw.write("여기까지만 입력");
bw.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
| cs |
java에서 html 만들기
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class MainClass {
public static void main(String[] args) {
String uri = "c:/filetest/basic.html";
try {
FileWriter fw = new FileWriter(uri);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("<html>");
bw.newLine();
bw.write("<body bgcolor = '#82E0AA'>");
bw.newLine();
bw.write("<h1>보여지는 글씨!</h1>");
bw.newLine();
bw.write("<form action = 'test.html' method ='get'>");
bw.write("<input type='text' name='txt'/>");
bw.write("<input type='submit' />");
bw.write("</form>");
bw.newLine();
bw.write("</body>");
bw.newLine();
bw.write("</html>");
bw.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
| cs |
java에서 다른 class 만들기
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class MainClass {
public static void main(String[] args) {
String uri = "c:/filetest/Main.Java";
try {
FileWriter fw = new FileWriter(uri);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("public class main{");
bw.newLine();
bw.write("public static void main(String[] args)");
bw.newLine();
bw.write("System.out.println(\"출력\")");
bw.newLine();
bw.write("}");
bw.newLine();
bw.write("}");
bw.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
| cs |
<Java - MySQL 연결>
1. JDBC 드라이버 로드
- Class.forName ("com.mysql.jdbc.Driver");
- 예외처리 ClassNotFoundException
2. 데이터베이스 연결 : java는 스스로 db접속불가, JDBC Driver 통해서만 접근 가능
- String db_url = "jdbc:mysql://localhost:3306/DB명" // 'localhost '= pc, ip number=127.0.0.1 // '3306'=port number, DB종류에 따라 다름, 가장먼저 접속 되는지 확인!
- ★ build path ★ project library에 mysql-connector-java-5.1.18-bin.jar 추가
- Referenced Libraries 추가됐는지 확인
- String db_id = "root"; // MySQL에서 id는 root로 고정됨
- String db_pw = "(p/w)" // 설치했을 때 p/w
- Connection con = null;
- con = DriverManager.getConnection(db_url, db_id, db_pw);
- 예외처리 : SQLException
* SQL에서 new db 생성
mysql> create database testdb;
Query OK, 1 row affected (0.01 sec)
| cs |
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MainClass {
public static void main(String[] args) {
// ★앞으로 계속 쓰이는 코드★ 반드시 숙지
String driver_name = "com.mysql.jdbc.Driver";
String db_url = "jdbc:mysql://localhost:3306/testdb";
String db_id = "root";
String db_pw = "1234";
Connection conn = null;
// import java.sql.Connection;
// 접속 결과 값 저장, 추후 자원 해제 시 필요
// 반드시 try-catch 밖에 선언
// driver에 연결되었는지 확인하는 code
try {
// 1. Class.forName() 이용해 해당 driver loading
Class.forName(driver_name);
System.out.println("MySQL Driver Load Successful");
// 2. DriverManager.getConnection(db_url, db_id, db_pw) 이용해 해당 DB 접속
conn = DriverManager.getConnection(db_url, db_id, db_pw);
System.out.println("DB connection Successful");
} catch (ClassNotFoundException e) {
System.out.println("ERR MySQL Driver Load : " + e.getMessage());
// DB driver 연결에 대한 exception
} catch (SQLException e) {
System.out.println("ERR Connect : " + e.getMessage());
// db url-id-pw에 대한 exception
// Access denied for user 'root'@'localhost' (using password: YES)
// ID/PW 잘못 입력한 경우, Oracle에서도 동일한 message
// Unknown database 'testdbsdgdsg'
// DB 명 잘못 입력한 경우
}
} // main() End
} // MainClass End
| cs |
MySQL> show 기존 dbs
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| test |
| testdb |
+--------------------+
4 rows in set (0.00 sec)
| cs |
mysql> use testdb;
Database changed
mysql> create table test (id varchar(10), pw varchar(10));
Query OK, 0 rows affected (0.06 sec)
mysql> desc test;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id | varchar(10) | YES | | NULL | |
| pw | varchar(10) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.01 sec)
| cs |
id 라는 char 데이터 10byte 짜리 생성, pw char data 10byte짜리 생성
* SQL의 문자/문자열
- char : 고정된 크기
- varchar : 가변형
- text : 약 20,000자 입력 가능
ex) 'abc'를 입력하는 경우
char(10) : abc + 7byte 고정 > 휴대폰번호, 주민번호 등 값 고정된 data에 활용
varchar(10) : abc만 입력해서 3byte > ID/PW, 글제목 등 가변 data에 활용
(Oracle에선 한글을 3byte로 잡음, varchar 대신 varchar2로)
* 숫자열 모두 int
mysql> insert into test (id, pw) values ('avc', '123');
Query OK, 1 row affected (0.03 sec)
mysql> insert into test values ('def', '456');
Query OK, 1 row affected (0.03 sec)
mysql> select * from test;
+------+------+
| id | pw |
+------+------+
| avc | 123 |
| def | 456 |
+------+------+
2 rows in set (0.00 sec)
mysql> select id from test;
+------+
| id |
+------+
| avc |
| def |
+------+
2 rows in set (0.00 sec)
mysql> delete from test;
Query OK, 2 rows affected (0.02 sec)
mysql> select * from test;
Empty set (0.00 sec)
| cs |
3. SQL문 실행
- Statement stmt = null;
- stmt = conn.createStatement();
- String sql = "insert into test_table values ('abc', '1234');
- int i = stmt.executeUpdate(sql);
- executeUpdate()는 실행횟수를 int로 반환
- 예외처리 : SQLException
// DB 명령을 실행할 객체
Statement stmt = conn.createStatement();
// 실행할 DB 명령
String insert = "insert into test values('abc', '777777777')";
// DB명령 실제 실행하는 method
int n = stmt.executeUpdate(insert);
// 실행 내용을 정수로 반환
System.out.println(n + "개를 삽입했습니다.");
| cs |
Java에서 db에 data 입력
- java와 mysql 한글 encoding이 다르기 때문에 입력하면 제대로 안뜸(? 표시)
mysql> select * from test;
+------+-----------+
| id | pw |
+------+-----------+
| abc | 123 |
| abc | 777777777 |
+------+-----------+
2 rows in set (0.00 sec)
| cs |
SQL에서 data 입력확인
// delete data
String delete = "delete from test";
int k = stmt.executeUpdate(delete);
System.out.println(k + "개를 삭제했습니다.");
| cs |
전체삭제, 확인
4. 조회 결과처리
5. 데이터베이스와 연결 해제
< SQL 기초 문법 >
mysql> select fieldNameList from tableName;
mysql> insert into tableName (fieldNameList) values (dataList);
mysql> delete from tableName;
ex)
select * from test ← test table의 모든 data 조회/선택
select id from test ← test table의 id 값들만 조회
select pw from test ← test table의 pw 값들만 조회
select pw,id from test ← test table이 pw와 id값들을 조회
insert into test (id) values ('ccc') ← test table의 id field에만 'ccc' 문자열 입력
insert into test (pw) values ('111') ← test table의 pw field에만 '111' 문자열 입력
insert into test (id, pw) values ('dd', '11') ← test table의 id field에 dd, pw field에 '11' 문자열 입력
insert into test (pw, id) values ('22', 'ee') ← test table의 pw field부터 '22', id field에 'ee' 입력
insert into test values ('dd', '11') ← test table 생성시 생성된 field 순서대로 값들 입력 // id = 'dd', pw ='11'
delete from test ← test table의 모든 data
| cs |
mysql> select * from test;
+------+------+
| id | pw |
+------+------+
| abc | 123 |
| def | 456 |
| ghi | 789 |
+------+------+
3 rows in set (0.00 sec)
mysql> select pw from test where id='abc';
+------+
| pw |
+------+
| 123 |
+------+
1 row in set (0.00 sec)
mysql> select id from test where pw='456';
+------+
| id |
+------+
| def |
+------+
1 row in set (0.00 sec)
mysql> delete from test where id='abc';
Query OK, 1 row affected (0.02 sec)
mysql> select * from test;
+------+------+
| id | pw |
+------+------+
| def | 456 |
| ghi | 789 |
+------+------+
2 rows in set (0.00 sec)
| cs |
SQL에서 조건절은 'where'
mysql> update test set pw='111' where id='def';
Query OK, 1 row affected (0.02 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from test;
+------+------+
| id | pw |
+------+------+
| def | 111 |
| ghi | 789 |
+------+------+
2 rows in set (0.00 sec)
| cs |
일부 data 변경 == 'update ~ set ~'
// id 'ghi' 의 pw 값을 '111'로 수정
// update tableName set updateField ='updateValue' where seachField = 'searchValue'
String update = "update test set pw='111' where id='ghi'" ;
int m = stmt.executeUpdate(update);
System.out.println(m + "개 수정되었습니다.");
| cs |
- Java에서 update
// select * from tableName
String select = "select * from test";
// ResultSet Class로 return; integer로 return 했던 이전 query와는 다름 주의
ResultSet rs = stmt.executeQuery(select);
// next() : 내부 포인터를 다음줄로 변경, 1 row 씩 출력
// rs.next() == 다음 data 읽을 수 있으면 true값 > while loop에 활용
while (rs.next()) {
// .getSring("fieldName")
System.out.println(rs.getString("id") + "\t" + rs.getString("pw"));
}
/*
* rs.next(); System.out.println(rs.getString("id")); // def
* System.out.println(rs.getString("pw")); // 111
*
* rs.next(); System.out.println(rs.getString("id")); // ghi
* System.out.println(rs.getString("pw")); // 111
*/
| cs |
- Java에서 select
⇒ SQL 4대 Query // ANSI Query; data 종류 무관 사용가능
- select ~ from ~
- delete from ~
- insert into ~ values (~)
- update ~ set ~
* 별도의 DBClass에서 기능별 method화
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBClass {
String driverName = "";
String dbURL = "";
String dbID = "";
String dbPW = "";
Connection conn = null;
public DBClass() {
} // DBClass() END
public void dbConnect() {
try {
Class.forName(driverName);
System.out.println("Success : Driver Loading");
conn = DriverManager.getConnection(dbURL, dbID, dbPW);
System.out.println("Success : DB Connection");
} catch (SQLException e) {
System.out.println("ERR Connect : " + e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println("ERR MySQL Driver Load : " + e.getMessage());
}
} // connect method
public ResultSet select() {
try {
Statement stmt = conn.createStatement();
String select = "select * from emp_table";
ResultSet rs = stmt.executeQuery(select);
while (rs.next()) {
System.out.println(rs.getString("name")
+ "\t" + rs.getInt("age")
+ "\t" + rs.getString("local")
+ "\t" + rs.getInt("years")
+ "\t" + rs.getBoolean("worker"));
}
} catch (SQLException e) {
System.out.println("ERR : SQLException" + e.getMessage());
}
String select = "select * from emp_table";
return null;
} // 전체 data 조회 select() method
} // class END
| cs |
댓글
댓글 쓰기