[포스코DX|SQL|4주] 18일차 수업
포스코DX X 비트교육센터 6기 - SQL | DBMS 설계 | JDBC
exerd
- 이클립스 help에서 new install software -> https://exerd.com/update 링크를 통해 설치 완료하기.
-
마리아디비 폴더의 models 폴더에 new 해서 other -> exerd file -> next 하고, mysql 5.1~5.8 선택, 해서 파일 만들기
- jdbc를 넣어야함. eclipse에서는. 그래서 pom.xml에 코드를 추가하거나, lib퍄일에 파일을 추가해주면 된다.
<dependencies>
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>3.0.8</version>
</dependency>
</dependencies>
dml
--
-- dml
--
-- insert
insert
into member(no, email, name)
values (12, 'sonrisa-bonita@naver.com', '한예원');
select * from member;
-- update
update member
set email = 'sonrisa@naver.com', name = '에옹'
where no = 12;
select * from member;
-- delete
delete
from member
where no =12;
select * from member;
DBNS 데이터베이스 설계
- DB설계 목적 : 중복성 제거, 정규화 시킴
데이터 모델
엔티티, 속성 : 정규화로 구분한다. 1NF
- 엔티티 : 단수, 하나의 인스턴스
ORM 솔루션 -> 자바(OOP)로 관계형 데이터를 좀더 같이 mapping해서 쓰는것.
1NF (도메인 분리 > 중복성 문제 해결)
- 앨범 엔티티에서 가수, 타이틀, 배급사, 노래 속성을 만들었음.
- 가수 한 명 당 노래가 여러개임.
- 그래서 노래 속성을 엔티티로 따로 빼줌.
- 그리고 앨범과 노래 엔티티로 분리함.
정리: 중복된 속성을 가진 엔티티는 그 안에 최소한 1개 이상의 다른 엔티티가 존재한다는 것을 의미한다.
- 속성인줄 알았는데, 엔티티였다!!
Primary key
- 유일한 식별자
식별관계
자기가 참조하는 키가 앨범의 프라이머리 키이자, 포린키.
비식별관계
참조키가 포린키
2NF (부분 종속성제거 : 중복제거)
- 식별자가 종속적일 때!
- 앨범 엔티티에서 가수, 배급사, 제목이 번호에 종속되어야한다.
- 가수는 번호에 종속적이지않다. 배급사도. 제목만!!
- 프라이머리 키가 아닌 속성들이 프라이머리 키에만 종속되어야한다.
2개 엔티티의 관계가 서로 관계가 있을 때, 중간의 fk를 담는 엔티티를 만든다.
- 가수 -> 앨범
- 앨범 -> 가수
일때, 가수 - 가수_앨범 - 앨범 으로…
- 최종 정리
3NF (이행적 종속성 제거)
식별할 수 없는 속성
ex. 장르약어는 장르에 종속되는데, 번호, 제목, 번호들에 종속되진 않음.
3NF 정도는 무시해도 큰 문제는 없다.
즉, 식별키를 제외한 나머지에서 종속이 나타날 때, 처리하는 것.
특성에 다 논리 물리 설정하고..!
서버에서 만들기
[root@lx ~]# mysql -p
Enter password:
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 12
Server version: 10.1.48-MariaDB Source distribution
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]> create user 'cdmall'@'192.168.%' identified by 'cdmall';
Query OK, 0 rows affected (0.00 sec)
MariaDB [(none)]> create database cdmall;
Query OK, 1 row affected (0.00 sec)
MariaDB [(none)]> grant all privileges on cdmall.* to 'cdmall'@'192.168.%';
Query OK, 0 rows affected (0.00 sec)
MariaDB [(none)]> flush privileges;
Query OK, 0 rows affected (0.00 sec)
그냥 폴더에 maven project 넣기
- 이클립스는 이게 안돼서 수작업으로 해주어야함.
-
intelliJ는 된다.
- 고로, 이클립스에서 수작업으로 프로젝트 안에 maven project 를 넣어보자.
첫째, 일단 외부에다가 new > maven project를 연다.
finish
둘째, 일반 프로젝트에 maven project 폴더를 로컬에서 넣어준다. 이후, maven project 내부에 있는 src, pom.xml만 놓고 지운다.
셋째, import 한다. jdbc-practices 선택 maven의 maven update project누름 설정해주기.
마지막! pom.xml을 수정해준다.
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.poscodx</groupId>
<artifactId>jdbc-practices</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>3.0.8</version>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.build.outputEncoding>UTF-8</project.build.outputEncoding>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
<build>
<finalName>jdbc-practices</finalName>
</build>
</project>
JDBC Connetion
package test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class TestConnection {
public static void main(String[] args) {
Connection conn = null;
try {
// 1. JDBC Driver Class 로딩
Class.forName("org.mariadb.jdbc.Driver");
// 2. 연결하기
String url = "jdbc:mariadb://192.168.0.178:3307/webdb?charset=utf8";
conn = DriverManager.getConnection(url, "webdb", "webdb");
System.out.println("연결성공!");
} catch (ClassNotFoundException e) {
System.out.println("드라이버 로딩 실패:" + e);
} catch (SQLException e) {
System.out.println("error:" + e);
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
SQL문도 사용해보기
package test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SelectTest01 {
public static void main(String[] args) {
searchEployees("ko");
}
public static void searchEployees(String keyword) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 1. JDBC Driver Class 로딩
Class.forName("org.mariadb.jdbc.Driver");
// 2. 연결하기
String url = "jdbc:mariadb://192.168.0.178:3307/employees?charset=utf8";
conn = DriverManager.getConnection(url, "hr", "hr");
// 3. Statement 객체 생성
stmt = conn.createStatement();
// 4. SQL 실행 -- 띄어쓰기 조심, 뒤에 세미콜론(;) 안 붙이도록 조심.
String sql = "select emp_no, first_name, last_name" + " from employees" + " where first_name like '%"
+ keyword + "%'" + " and last_name like '%" + keyword + "%'";
rs = stmt.executeQuery(sql);
// 5. 결과 처리
while (rs.next()) {
Long empNo = rs.getLong(1);
String firstName = rs.getString(2);
String lastName = rs.getString(3);
System.out.println(empNo + ":" + firstName + ":" + lastName);
}
} catch (ClassNotFoundException e) {
System.out.println("드라이버 로딩 실패:" + e);
} catch (SQLException e) {
System.out.println("error:" + e);
} finally {
try {
// 6. 자원정리
if(rs!=null) {
rs.close();
}
if(stmt!=null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}