202401to07
  • 2024.05.29.수.보안 day39
    2024년 05월 29일 13시 01분 39초에 업로드 된 글입니다.
    작성자: 202401to07

    DB시작~

     

    [ maria 마리아 디비 ]

    192.168.10.10 미니 

    192.168.10.20 록키 

    [ 마리아 디비 설치 ]

    dnf install maria*

    systemctl list-unit-files |grep maria
    service mariadb restart
    systemctl enable mariadb
    systemctl list-unit-files |grep maria

    [root@sevas10 ~]# netstat -lntup |grep mysql
    tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN      36829/mysqld

     

     

    [mysql 한글설정]
    vi /etc/my.cnf

    [client-server]
    character_set_server=utf8
    [client]
    default-character-set=utf8

    service mariadb restart
    mysql -u root -p

    엔터 
    \s                      : utf8로 바뀐것 확인
    show variables like 'c%'

    ;                        : 전부 utf8로 나오는것 확인

     


    DDL (생성 정의 삭제 ) (data definition language)  < DB, TABLE>
    DB관리자가/설계자가 사용 (데이타 구조를 정의 하는 언어)
    create , alter , drop , truncat
    생성     재정의  삭제  초기화

    DML (데이타 수정 = 값 삽입) <data manipulation language>  < TABLE > 
    테이블내 값 삽입 수정 삭제 조회 (DATA를 조작하기 위한 언어)
    insert , update , delete , select 
    삽입    수정       삭제     조회     <<<<<<<(value)

    DCL (데이타 제어) <data control language> 
    복구  권한 할당 DBMS를 제어하기 위한 언어
    grant   revoke  commit  rollback
    권한부여  권한해제 실행적용 복구 

    **스키마 ( 데이터 구조를 정의 )  = schema   (준비물) : DB, 테이블
    SEVAS
    no 이름 수강과목 성적

    1.외부스키마
    질의나 프로그래밍 언어를 이용해서 접근하는 베이터 베이스 
    [ no 이름 수강과목     성적 ]

    2.개념스키마
    개체 데이터 유형 관계 사용자 연산 제약조건등을 정의
    (desc 에서 나오는 필드 타입 형식등이 개념적 스키마 )
    no int(2)  이름 char(10)   수강과목 varchar(20) 성적 int(3) 

    3.내부스키마
    물리적 저장 구조에 대한 정의
    데이터 메모리 , DB의 length값  필드들의 바이트와 osffest인덱스 등등
    용량으로 표현되는 것들

    int  = 4byte
    문자 = 1byte
    sevas length=10
    no   byte(8) offset=0
    이름  byte(10) offset=8 
    수강과목 byte(2)  offset=10

     


    #DATABASE 구현#
    1. 요구사항분석  : 데이타 수집
    2. 개념적 설계     : 스키마를 만들기 위한 데이타 DB,TABLE로 구분/  DB,TABLE 정의
    3. 논리적 설계     : 스키마 속성을 정의 속성 int varchar 권한 / field values  속성값
    4. 물리적 설계     : 논리적 설계를 사용한 스키마의 SQL구문 정의 /   alter modify
    5. 구현                 : DBMS사용 , SQL 쿼리문구현

     

    varchar(10)     a 입력    = 1byte     / 가변형
    char(10)         a 입력    = 10byte

     


    DDL 

    데이터 정의

    순서 :  DB - table  - field -  value

    create, alter, drop, truncate 

     

    1. DB보기
    show databases;

     

    2. DB 생성 (create)
    create database korea;

    show databases;


    3. DB 삭제 (drop)

    drop database korea2;

    show databases;

     

    4. DB 이동 (use)

    use korea

    \s                 : 확인

     

    5.table 확인
    show tables;

     

    6. tables 생성
    create table class (
    id(필드,외부스키마) varchar(40(내부스키마)),
    age int(2),
    atk int(2)
    );

     

    show tables;

     

    7.table 보기 /  포멧확인
    describe class;

    desc class;

     

    8.테이블 삭제 

    drop table class2;


    재정의 종류   alter table class

    1. modify 

    2. change

    3. add

    4. drop

     

     

    1. [modify  타입변경]

    alter table class

    modify age(필드) varchar(20);

     

    2. [change 필드명 & 타입변경]   : 외부스키마(개념도 같이)와 타입을 바꿀수있다= 좀 더 범용적이다 

    alter table class

    change age 나이 int(2),

    change atk 공격 int(2);

     

    3. [add 필드추가 및 고유값 추가]

    alter table class
    add 순번 int(10) first,
    add 이름 varchar(20) after 나이,
    add 방어 int(2);

    alter table class add 사번 int(10) after 순번;

     

    **mysql은 시퀀스idx가 없다 , 순서 없이 적재가된다 , 그래서 first와 after로 위치를 잡는다** 


    제약 조건

     

    DATABASE의 제약조건 4가지
    1. primary key     : 고유값, 널 X    (unique + not null)
    2. unique key      : 고유값, 널 O
    3. not null            :              널X
    4. foreigen key    :  외래키

     

    ###고유값 생성

    alter table class

    add primary key(이름),

    add unique index (순번);

    desc class;

     

     

    ###고유값 삭제

    [unique key]

    drop index 순번 on class;

    desc class;

     

    [primary key]

    alter table class 

    drop primary key;

    desc class;

     

    alter table class
    modify 이름 varchar(20) null;                : primary 키는 삭제해도 not null 이 남아있어서 null로 수정을 해줘야한다 

     


     

    unsigned  : 음수의 지역을 양수의 지역으로 바꾼다(절댓값)

                        ex) -128 +128 = unsigned 256

    auto_increment  : 자동 인덱스 (에러또한 인덱스 왜? 유결성땜에)

    default ' ' : null이 나왔을때 '  ' 이 값이 들어간다 

    text  : 긴 내용 , 제일 중요하지 않는 문자열

    reg_date  : 등록시간

    index : 인덱스를 주어 검색 속도를 올려준다 


    create table sevas2 ( 
    no int unsigned auto_increment primary key, 
    id varchar(20) unique, 
    name varchar(20) not null, 
    class varchar(20) default 'student', 
    address text not null, 
    reg_date datetime,

    index (id));


    고유값이 2개 필요할경우
    create table sevas3 (                   ---------- sevas2보다 이 방법을 많이 쓴다 
    no int unsigned auto_increment, 
    id varchar(20), 
    name varchar(20) not null, 
    class varchar(20) default 'student', 
    address text not null, 
    reg_date datetime,
    index (id),
    primary key(no,id));       -- primary도 우선순위가 있다 no > id


    create table sevas4(
        no int unsigned auto_increment unique not null,
        id varchar(20) primary key,
        name varchar(20) not null,
        class varchar(20) default 'student',
        address text not null,
        reg_date datetime,
        index (no));


    create table sevas5(                           ---------------------------------에러 
        no int unsigned auto_increment primary key,
        id varchar(20) primary key,
        name varchar(20) not null,
        class varchar(20) default 'student',
        address text not null,
        reg_date datetime,
        index (no));


    create table sevas6(                                                     
        no int unsigned auto_increment unique not null,      ----- 모두 noy null을 주면 최초를 primary로 자동을 됨
        id varchar(20) unique not null,
        name varchar(20) unique not null,
        class varchar(20) default 'student',
        address text not null,
        reg_date datetime,
        index (no));

     


    create table sevas7(                                                
        no int unsigned unique not null,
        id varchar(20) not null,                                                -------- MUL 후보키 
        name varchar(20) not null,
        class varchar(20) default 'student',
        address text not null,
        reg_date datetime,
        unique (id,name)
    );


    create table sevas8(                                                
        no int unsigned not null,
        id varchar(20) not null,                                               
        name varchar(20) not null,
        class varchar(20) default 'student',
        address text not null,
        reg_date datetime,
        unique (no, id,name)
    );

     


    **테이블 데이타 초기화**
    truncate table class;  <<< 값만 삭제

     

    DDL /  제약조건 끝 ~


    DML

    데이타 수정 = 값 삽입 <data manipulation language>  < TABLE > 
    테이블내 값 삽입 수정 삭제 조회 (DATA를 조작하기 위한 언어)
    insert , update , delete , select 
    삽입    수정       삭제     조회     <<<<<<<(value)


    [primary key 삭제]
    alter table class drop primary key;

     

    [primary key 삭제했으니 null로 복구]

    alter table class modify 이름 varchar(40) null;

     

    [primary key 1개만 생성- 순번 ]
    alter table class add primary key (순번);

     

    drop table class;


    primary  빈칸도 값으로 인정 

    not null : null o , 중복 o 

     

    update class set 방어='7';  <<<< 방어가 전부 7이됨

    update class set 사번='0', 공격='0'  where 이름='';    이름이 없는 row의 사번과 공격 0으로 수정

     

     

     

    update 테이블 set 칼럼='값';

    delete from 테이블 where  칼럼='값';

    select 컬럼 from 테이블  where  칼럼='값';

    select * from 테이블  order by 컬럼 desc;   내림차순

    select * from 테이블  order by 컬럼 asc;   오름차순

     

    select * from class  where 나이='25' and 방어='9';

    select * from class  where 나이='25' or 방어='9';

     

    select 이름,사번,나이 from class 
    where 나이 like '%2%' and 공격 >= 60  
    order by 사번 asc;

     

     select 나이 from class  

    where 나이 like '%2%' and 공격 >= 60   

    order by 사번 asc 

    limit 2,2;

     

    select 이름,사번, (나이+20) from class  

    where 나이 like '%2%' and 공격 >= 60   

    order by 사 번 asc 

    limit 2,2;;

     


    이제 192.168.10.10 미니 ~

    이제 db에 연결해봅시다.


    [설치]
    yum install mariadb* -y
    yum install php-* --skip-broken


    [서비스 실행]
    service mariadb restart


    [자동실행]
    systemctl enable mariadb


    [포트번호확인 (3306/tcp)]
    netstat -lntup |grep mysql


    [접속]
    mysql -u root -p (엔터,엔터 <비밀번호 없어요~>)


    [상태확인]
    \s


    [한글설정]

    vi /etc/my.cnf
    [mysqld]
    character-set-server=utf8
    [client]
    default-character_set=utf8

     

    [적용]
    service mariadb restart

     

    [한글적용확인]
    mysql -u root -p
    \s                          <<<<<<<<< 모두 utf8 인지 확인

     



    vi /var/www/html/db/index.html을 만들어봐요.

    <?php
    session_start();
    mysql_connect("localhost","root","") or die ("NET 연결오류");    : 로컬호스트 root 비번
    echo "connect success";
    ?>


    mv index.html  index.php     : index.html일때는 안나옴 / connect success가 출력

    service mariadb stop    : 하면 웹에 NET 연결오류
    service mariadb start    : 하면 웹에 connect success

     

    php는 쿠키를 받아서 세션을 내린다 

    세션안에는 계정에 대한 정보들이 있다 


    mysql -u root -p

    create database sevas;

     

    DB연동코드 
    mysql_select_db(sevas) or die ("DB 연결실패");
    echo "Connect DB<br>?";

     

    create table class (
    c_no int unsigned auto_increment,
    id char(40) not null unique,
    pw char(40) not null,
    nick varchar(40) not null,
    date  datetime not null,
    primary key(c_no)
    );

     

    cd /var/www/html/proc
    vi login_proc.php

    <?php
    $id=$_POST['id'];
    $pw=$_POST['pw'];
    #echo "$id<br>";
    #echo "$pw<br>";

    session_start();
    mysql_connect("localhost","root","") or die ("mysql Fail");
    echo "Connect Mysql<br>";
    mysql_select_db(sevas) or die ("DB Fail");
    echo "Connect DB<br>";

    $sql="select id,pw from class where id='$id' and pw='$pw'";
    $exec=mysql_query($sql);
    $result=mysql_fetch_array($exec) or die ("Login Fail");
    echo "Login Success<br>";
    ?>

     

     

     

     

     

     

    '보안' 카테고리의 다른 글

    2024.06.03.보안 day41  (1) 2024.06.03
    2024.05.30.목.보안 day40  (0) 2024.05.30
    2024.05.28.화.보안 day38  (0) 2024.05.28
    2024.05.27.월.보안 day37  (1) 2024.05.27
    2024.05.24.금.보안 day36  (0) 2024.05.24
    댓글