Tue/Jan/14 [Java] day11. MySQL 기본 함수 추가,

Tue/Jan/14
[Java]
day11.

< 전일 Java-SQL 복습&추가설명 >

Connection
; DB작업 끝날때까지 소멸되면 안되는 object

Statement
; 반드시 connection object 통해서 statement object 생성시켜야 함
; new 연산자로 생성 불가!

method of Statement

  • executeQuery
    • select 구문에서만 사용가능
    • ResultSet type(표)으로 결과값 저장&return, 한 묶음씩 보관, 한 record(셀)씩 호출
    • ArrayList 처럼 numbering 된 것이 아님, for loop 사용 어려움
    • SQLException : Connection에서의 Exception과 동일
  • executeUpdate
    • insert, delete, update query
    • query 성공한 record 갯수를 int type으로 return
* SQL 활용은 BigData에서도 동일하게 쓰인다

* ResultSet select method에서도 외부 data를 쓰기 때문에 예외문 필요


<MySQL 기본문법 추가>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| test               |
| testdb             |
+--------------------+
4 rows in set (0.00 sec)
mysql> show tables;
+------------------+
| Tables_in_testdb |
+------------------+
| emp_table        |
| test             |
+------------------+
2 rows in set (0.03 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)
mysql> desc emp_table;
+--------+------------+------+-----+---------+-------+
| Field  | Type       | Null | Key | Default | Extra |
+--------+------------+------+-----+---------+-------+
| name   | varchar(5| YES  |     | NULL    |       |
| age    | int(11)    | YES  |     | NULL    |       |
| local  | char(2)    | YES  |     | NULL    |       |
| years  | int(11)    | YES  |     | NULL    |       |
| worker | tinyint(1| YES  |     | NULL    |       |
+--------+------------+------+-----+---------+-------+
5 rows in set (0.01 sec)
cs

1
2
3
4
5
6
7
mysql> select count(*from emp_table;
+----------+
| count(*|
+----------+
|       10 |
+----------+
1 row in set (0.01 sec)
cs

모든 database들은 count 내재; 함수명이 아닌 field명

mysql> select max(age) from emp_table;
+----------+
| max(age) |
+----------+
|       33 |
+----------+
1 row in set (0.01 sec)
mysql> select min(age) from emp_table;
+----------+
| min(age) |
+----------+
|       28 |
+----------+
1 row in set (0.00 sec)
mysql> select sum(age) from emp_table;
+----------+
| sum(age) |
+----------+
|      294 |
+----------+
1 row in set (0.00 sec)
mysql> select avg(age) from emp_table;
+----------+
| avg(age) |
+----------+
|  29.4000 |
+----------+
1 row in set (0.00 sec)
cs

기본 함수 : max(var) / min(var) / sum(var) / avg(var)
; Oracle도 동일
; java for loop으로 할 일이 크게 줄어듦

mysql> select sum(age) from emp_table where local = 'KR';
+----------+
| sum(age) |
+----------+
|      113 |
+----------+
1 row in set (0.00 sec)
mysql> select avg(age) from emp_table where local = 'KR';
+----------+
| avg(age) |
+----------+
|  28.2500 |
+----------+
1 row in set (0.00 sec)
cs

mysql> select * from emp_table where age>30;
+------+------+-------+-------+--------+
| name | age  | local | years | worker |
+------+------+-------+-------+--------+
| B    |   31 | JP    |     3 |      0 |
| F    |   32 | US    |     5 |      1 |
| I    |   33 | EU    |     6 |      1 |
+------+------+-------+-------+--------+
3 rows in set (0.00 sec)
mysql> select * from emp_table where age>20 AND years=2;
+------+------+-------+-------+--------+
| name | age  | local | years | worker |
+------+------+-------+-------+--------+
| D    |   29 | KR    |     2 |      1 |
| E    |   28 | US    |     2 |      0 |
| H    |   29 | EU    |     2 |      0 |
+------+------+-------+-------+--------+
3 rows in set (0.00 sec)
cs

기본연산함수와 조건문 where

mysql> select * from emp_table order by age;
+------+------+-------+-------+--------+
| name | age  | local | years | worker |
+------+------+-------+-------+--------+
| A    |   28 | KR    |     1 |      1 |
| G    |   28 | KR    |     1 |      0 |
| J    |   28 | KR    |     1 |      0 |
| E    |   28 | US    |     2 |      0 |
| C    |   28 | JP    |     1 |      1 |
| D    |   29 | KR    |     2 |      1 |
| H    |   29 | EU    |     2 |      0 |
| B    |   31 | JP    |     3 |      0 |
| F    |   32 | US    |     5 |      1 |
| I    |   33 | EU    |     6 |      1 |
+------+------+-------+-------+--------+
10 rows in set (0.01 sec)
mysql> select * from emp_table order by age desc;
+------+------+-------+-------+--------+
| name | age  | local | years | worker |
+------+------+-------+-------+--------+
| I    |   33 | EU    |     6 |      1 |
| F    |   32 | US    |     5 |      1 |
| B    |   31 | JP    |     3 |      0 |
| D    |   29 | KR    |     2 |      1 |
| H    |   29 | EU    |     2 |      0 |
| G    |   28 | KR    |     1 |      0 |
| A    |   28 | KR    |     1 |      1 |
| E    |   28 | US    |     2 |      0 |
| C    |   28 | JP    |     1 |      1 |
| J    |   28 | KR    |     1 |      0 |
+------+------+-------+-------+--------+
10 rows in set (0.00 sec)
cs

정렬

mysql> select * from emp_table where age<30 order by age;
+------+------+-------+-------+--------+
| name | age  | local | years | worker |
+------+------+-------+-------+--------+
| A    |   28 | KR    |     1 |      1 |
| C    |   28 | JP    |     1 |      1 |
| E    |   28 | US    |     2 |      0 |
| G    |   28 | KR    |     1 |      0 |
| J    |   28 | KR    |     1 |      0 |
| D    |   29 | KR    |     2 |      1 |
| H    |   29 | EU    |     2 |      0 |
+------+------+-------+-------+--------+
7 rows in set (0.00 sec)
mysql> select * from emp_table where age<30 AND years= 2 order by age;
+------+------+-------+-------+--------+
| name | age  | local | years | worker |
+------+------+-------+-------+--------+
| E    |   28 | US    |     2 |      0 |
| D    |   29 | KR    |     2 |      1 |
| H    |   29 | EU    |     2 |      0 |
+------+------+-------+-------+--------+
3 rows in set (0.00 sec)
cs

조건과 정렬이 함께 주어질 때는 선 조건 후 정렬

mysql> select * from emp_table
    -> where age > 20
    -> order by age desc;
+------+------+-------+-------+--------+
| name | age  | local | years | worker |
+------+------+-------+-------+--------+
| I    |   33 | EU    |     6 |      1 |
| F    |   32 | US    |     5 |      1 |
| B    |   31 | JP    |     3 |      0 |
| D    |   29 | KR    |     2 |      1 |
| H    |   29 | EU    |     2 |      0 |
| G    |   28 | KR    |     1 |      0 |
| A    |   28 | KR    |     1 |      1 |
| E    |   28 | US    |     2 |      0 |
| C    |   28 | JP    |     1 |      1 |
| J    |   28 | KR    |     1 |      0 |
+------+------+-------+-------+--------+
10 rows in set (0.00 sec)
cs

줄바꾸기로 해도 가능

mysql> update emp_table set years=years+1;
Query OK, 10 rows affected (0.06 sec)
Rows matched: 10  Changed: 10  Warnings: 0
mysql> select * from emp_table;
+------+------+-------+-------+--------+
| name | age  | local | years | worker |
+------+------+-------+-------+--------+
| A    |   28 | KR    |     2 |      1 |
| B    |   31 | JP    |     4 |      0 |
| C    |   28 | JP    |     2 |      1 |
| D    |   29 | KR    |     3 |      1 |
| E    |   28 | US    |     3 |      0 |
| F    |   32 | US    |     6 |      1 |
| G    |   28 | KR    |     2 |      0 |
| H    |   29 | EU    |     3 |      0 |
| I    |   33 | EU    |     7 |      1 |
| J    |   28 | KR    |     2 |      0 |
+------+------+-------+-------+--------+
10 rows in set (0.00 sec)
cs

years 1씩 증가하기
> update ~ set ~

mysql> update emp_table set years=years+1, age=age+1;
Query OK, 10 rows affected (0.03 sec)
Rows matched: 10  Changed: 10  Warnings: 0
cs

조건 추가는 ' , '로 구분

mysql> update emp_table set years=years+1, age=age+1;
Query OK, 10 rows affected (0.03 sec)
Rows matched: 10  Changed: 10  Warnings: 0
mysql> update emp_table
    -> set age = age+1
    -> where local = 'KR';
Query OK, 4 rows affected (0.03 sec)
Rows matched: 4  Changed: 4  Warnings: 0
mysql> update emp_table
    -> set worker="regular"
    -> where worker = 1;
ERROR 1366 (HY000): Incorrect integer value: 'regular' for column 'worker' at row 1
cs


⇒ 기본문법만으로도 게시판 기본 기능 구현 가능


<ex. mySQL에 있는 자료로 java에서 html table 만들기>


* JAVA code 구성
  • Class : code의 최소단위
    • public  class className{ // 선언문만 작성 가능, 사용은 불가 }
  • 선언문
    • class 내부에
    • 변수 선언 : data type name; 또는 data type name = initial valuel;
    • 생성자 선언 : 접근제한자 className(  ){  }
    • method 선언 : 접근제한자 returnType methodName( parameterType parameterName ) {  }
  • 선언된 method, loop, 조건문 사용은 반드시 method/생성자 내부에서
* HTML Hyper Text Mark-up Language : 웹 브라우저 내에 문서를 표현할 수 있는 언어
  1. Structure
    1. 전체 구조
      • <html>
      • <head>
        • <title>"Tab Title" </title>
      • </head>
      • <body>
        • ...contents...
      • </body>
      • </html>
    2. table type으로 표현할 경우
    • <body> </body> 사이에
    • table 전체 : <table> table 내부 </table>
    • table 내부 
      • <tr>  </tr> : 한 줄
        • <th> </th> : 제목
        • <td> </td> : 데이터 표현

* 조회된 data를 HTML에 입력

  1. 빈 file 생성하여 file 내부에 HTML code 적기
    1. file 내부에 글을 쓸 수 있는 class == FileWriter.class
    2. FileWriter fw = new FileWriter("c:/filetest/result_table.html");
    • FileWriter 객체 생성, file은 없어도 directory는 있어야함
  2. 줄 단위로 글 쓰기 위해 필요한 class == BufferedWriter.class
    1. BufferedWriter bw = new BufferedWriter(fw);
    • BufferedWriter 객체 생성, 단 file 관련 object(여기선 fw) 필요!
  3. 실제 파일에 글을 쓰는 method == bw.write("  ");
  4. 줄을 바꿔주는 method == bw.newLine();
  5. 내용 입력 끝나면 반드시 bw.close(); // 저장하고 file 닫는 method
public static void htmlWriter(ResultSet rs) {
        
        String url = "c:/filetest/table.html";
        try {
            FileWriter fw = new FileWriter(url);
            BufferedWriter bw = new BufferedWriter(fw);
            
            bw.write("<html>");
            bw.newLine();
            bw.write("<head>");
            bw.newLine();
            bw.write("<title>    !test table!    </title>");
            bw.newLine();
            bw.write("</head>");
            bw.newLine();
            bw.newLine();
            bw.write("<body>");
            bw.newLine();
            bw.write("<table border=1 style=\"width:30%\">");
            bw.newLine();
            bw.write("<tr>    <th>name</th>    <th>age</th>    <th>local</th>    <th>years</th>    <th>worker</th>    </tr>");
            bw.newLine();
            
            while (rs.next()) {
                bw.write("<tr>"
                        + "<td>" + rs.getString("name"+ "</td>" 
                        + "<td>" + rs.getInt("age"+ "</td>    " 
                        + "<td>" + rs.getString("local"+ "</td>"
                        + "<td>" + rs.getInt("years"+ "</td>" 
                        + "<td>" + rs.getBoolean("worker"+ "</td>"
                        + "</tr>");
                bw.newLine();
            }
            
            
            bw.write("</table>");
            bw.newLine();
            bw.write("</body>");
            bw.newLine();
            bw.newLine();
            bw.write("</html>");
            bw.newLine();
            bw.close();
        } catch (IOException e) {
            System.out.println("ERR : File Connection" + e.getMessage());
        } catch (SQLException e) {
            System.out.println("ERR : ResultSet data : "+e.getMessage()); 
        }
        
    }
cs

★★★ method parameter를 ResultSet로 받아서, method 내부에서는 관련 작업만 할 수 있도록 ★★★ 

html class에서 import하고 뭐했다가 안되서 dataclass로 옮겼다가 다시 옮기고 난리였는데 이런 쉬운 방법이..
무엇보다 dataclass select() method 구성이 잘못된걸 못찾았음..



<The End>

댓글

가장 많이 본 글