MongoDB 설치후 데이터베이스 위치, 로그, 인증 등에 관련한 서버 구성과 설정을 정리한다.
MongoDB 2.6 과 MongoDB Community Edition 3.x 버전을 사용했다.
mongoDB 접근제어
mongoDB 는 설치과정 중에 인증과 관련해 설정하는 부분이 없어서 설치 후 누구나 DB에 접속 할 수 있다. 인증을 추가해 데이터베이스 관리자와 데이터베이스 사용자로 구분해서 이용하고, 각 데이터베이스의 사용자는 허가된 역할(Role)을 가지고 데이터베이스에 접근 가능하도록 구성한다.
mysql >createuser foo@localhost identified by'password'; mysql >createuser'foo'@'%' identified by'password';
혹은
1
insert into user (host, user, password) values ('localhost', 'hiru', 'password('hirururu'));
사용자 제거 mysql > drop user ‘hiru’; mysql > delete from user where user =’hiru’
사용자 생성시 다음같이 1396 에러는 CREATE USER/GRANT 명령으로 사용자와 권한을 추가/관리해야 하는데 mysql.db, mysql.user 테이블을 직접 조작하다가 일관성이 깨졌기 때문
1 2
mysql> create user 'shopuser'@'localhost' identified by ')12345'; ERROR 1396 (HY000): Operation CREATE USER failed for 'shopuser'@'localhost'
제대로 사용자를 삭제하고
drop user shopuser@localhost
flush privileges; 로 갱신해 준다.
권한 주기
권한을 추가하고 삭제하기 위해서, GRANT와 REVOKE의 명령을 사용한다. GRANT 명령 등으로 데이터베이스 사용자가 데이터베이스 자원에 접근하는 권한을 만들 수 있다.
GRANT ALL privileges ON DB_NAME.TABLE TO USER_ID@[HOST] IDENTIFIED BY ‘PASSWORD’ GRANT [SELECT,DELETE,INSERT,UPDATE,] ON DB_NAME.TABLE TO USER_ID@[HOST] IDENTIFIED BY ‘PASSWORD’
현재 머신에서만 접속할 수 있는 사용자 계정, 외부, 원격에서 접속할 수 있는 사용자 계정을 추가해 준다.
1 2 3
mysql> use mysql; # mysql system db mysql>GRANTALL privileges ON mydb.*TO foo@localhost IDENTIFIED BY'*****'; mysql>GRANTALL privileges ON mydb.*TO foo@'%' IDENTIFIED BY'*****';
혹은
1 2
grant select, insert, update, delete on mydb.* to foo@host identified by 'password'; mysql > grant select, insert, update, delete on dbname.table to userid@'192.168.%' identified by 'password';
권한을 확인하는 방법
1 2
mysql >show grants for foo@localhost mysql >show grants for'foo'@'%';
변경된 권한을 적용하기
1
mysql > flush privileges;
권한을 삭제하는 방법
1
mysql > revoke all on dbname.table from username@host
추가한 사용자는 SELECT로 확인할 수 있다.
1
mysql> select host,authentication_string from user where user='foo';
studnets.txt 파일을 읽어들이는 것은 스크립트 파일을 작성하거나 mysql에서 직접 실행할 수 있다. 먼저 스크립트 파일 students.sql은 다음과 같다.
1 2 3
use mydb; load data local infile "student.txt" intotable student fields terminated by',' ;
이제 mysql 클라이언트에서 데이터를 읽어 들인다.
1 2
mysql>source students.sql;
데이터 조회
SELECT [DISTINCT] select _expr essi on FROM table_list WHERE where_definition ORDER BY col_name [ASC|DESC] GROUP BY col _name_list LIMIT [offset ], rows
예제-1) 전체 교수 리스트를 출력하는 SQL 검색 문을 작성하라. mysql > sel ect * fromprof;
예제-2) 전체 교수 리스트를 이름순서로 출력하는 검색 문을 작성하라. mysql > sel ect * fromprof order by pname;
예제-5) 전체 교수 리스트를 이름 역순으로 출력하는 검색 문을 작성하라. mysql > sel ect * fromprof order by pname desc;
전체 교수 리스트를 학과별로 출력하는 검색 문을 작성하라. mysql > sel ect * fromprof order by pdept, pname;
예제-4) 국문학과 교수 리스트를 이름순서로 출력하는 검색 문을 작성하라. mysql> select * from professor where pdept =’국문학과’;
JOIN
“FROM 테이블명 AS 별명” 구문은 SQL 문장에서 별명으로 테이블을 참조하 는 역할은 한다.
예제-6) MySQL 과목을 강의하는 교수님의 이름, 전화번호와 강의실을 검색 하는 문장을 작성하라. mysql> select p.pname, p.pphone, c.croom from professor p, course c, lecture l where c.cname=’MySQL’ and c.ccode=l.lccode and l.lpcode=p.pcode;
예제-7) ‘김구’ 교수님이 강의하는 과목명, 강의 시수와 강의실을 검색하는 문장을 작성하라.
1 2 3 4
select c.cname, c.ctime, c.croom from professor as p, course as c, lecture as l where p.pname ='김 구'and p.pcode = l.lpcode and l.lccode = c.ccode;
예제-8) 각 학생이 수강 신청한 과목에 대해서 학생이름, 전화번호, 과목명, 강의실, 강의 시수를 검색하는 문장을 작성하라.
1 2 3 4
select s.sname, s.sphone, c.cname, c.ctime, c.croom from student as s , course as c, register as r where s.scode = r.rscode and r.rccode = c.ccode orderby s.sname, c.cname;
sub-query
예제-9) 각 학생이 신청한 총 학점을 구하는 검색식을 작성하라.
1 2 3 4
select s.sname, s.sdept, s.sphone, sum(c.ctime) from student as s , course as c, register as r where s.scode = r.rscode and r.rccode = c.ccode groupby s.sname;
WHERE 조건절에 해당하는 결과를 GROUP BY 구절에 명시된 s.sname 필드에 따라 그룹으로 결과를 분류하고 난 후, SELECT 필드에 SUM(c.cti me) 함수를 사용해서 c.cti me 필드에 대한 합을 구함으로써 각 학 생이 신청한 총 학점를 구할 수 있다.
예제-10) 각 학과별 교수님은 몇 분인지 구하는 검색식을 작성하라.
1 2 3
select pdept, count(*) from professor groupby pdept;
LIMIT 구절
예제-11) 페이지 크기가 2 일 때, (예제-8)의 결과에서 두 번째 페이지를 검색하는 SQL문장은 작성하라. select s.sname, s.sphone, c.cname, c.ctime, c.croom fromstudent as s , course as c, regi ster as r where s.scode = r.rscode and r.rccode = c.ccode order by s.sname, c.cname limit 2, 2;
마지막 행의 limit 2, 2구절에서, 첫 번째 인자는 오프셋(offset)으로 검 색 결과 레코드들의 순번을 의미한다. 오프셋 값은 0 부터 지정하기 때문에 오프셋값2는전체레코드중에서세번째레코드를가리킨다. 두번째는 인자는 출력하는 레코드 수(rows)를 의미한다. 따라서, 레코드 수 2 는 2 개 의 레코드를 출력하라는 의미가 된다.
예제-12) 교수테이블에서 ‘김 구’ 선생님의 이름을 ‘하은용’ 교수님으로 변 경하는 문장을 작성하라. update prof set pname =’하은용’ where pname =’김구’;
예제-13) 지도 테이블의 교수코드가 ‘P007’ 인 레코드들을 모두 ‘P005’ 로 변경하라. update advise set apcode =’P005’ where apcode =’P007’;
예제-14) 강의 시수가 2인 과목들의 강의 시수를 하나 증가 시키고, 강의실 을 Lab1로 변경하라. update course set ctime=ctime + 1, croom=’Lab1’ where ctime=2;
Delete
DELETE FROM tbl_name [WHERE where_definition] [LIMIT rows]
예제-15 ) 국문학과 학생 레코드를 삭제하는 문장을 작성하라. delete fromstudent where sdept =’국문학과’;
PyMySQL 튜토리얼
PyMySQL 설치
1
$ pip install PyMySQL
만약 pip 로 설치가 안되면 다음 같이 setup.py를 이용해 직접 설치 할 수 있다. $ # X.X is the desired PyMySQL version (e.g. 0.5 or 0.6). $ curl -L https://github.com/PyMySQL/PyMySQL/tarball/pymysql-X.X | tar xz $ cd PyMySQL* $ python setup.py install $ # The folder PyMySQL* can be safely removed now.
mysql 설치작업이 끝나면 데몬을 구동하기 위한 초기화 작업이 필요하다. 다음과 같이 작업이 완료되면 최초 설치 작업은 마무리 된다.
mysql 환경설정 기본 파일 복사
1
$ cp ./support-files/my-default.cnf /etc/my.cnf
mysql 초기화
1 2
$ cd /usr/local/mysql $ /usr/local/mysql/scripts/mysql_install_db –user=mysql
mysql 서비스 스크립트 및 서비스 설정
Mysql 설정이 완료되면 부가적으로 서비스의 스크립트와, 부팅 시 자동으로 서비스가 올라오도록 아래와 같은 기본 설정을 추가한다.
mysql 서비스 스크립트 및 서비스 runlevel 등재
1 2
$ cd /usr/local/mysql $ cp -a support-files/mysql.server /etc/init.d/mysqld # ln -s /etc/init.d/mysqld /etc/rc3.d/S90mysqld
Start
mysql-server 를 설치하며 만든 root 사용자 패스워드를 사용해서 데이터베이스에 접속한다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
$ mysql -u root -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 1 Server version: 5.6.26 MySQL Community Server (GPL)
Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | +--------------------+ 3 rows in set (0.00 sec)
# 현재 머신에서만 접속할 수 있는 사용자 계정 mysql>GRANTALL privileges ON*.*TO ID@localhost IDENTIFIED BY'*****'; # 외부, 원격에서 접속할 수 있는 사용자 계정 mysql>GRANTALL privileges ON*.*TO ID@'%' IDENTIFIED BY'*****';
localhost 머신의 MySQL 데이터베이스에 myid라는 이름의 아이디를 만들고, 패스워드는 password로 설정
사용자 데이터베이스 사용
새로 생성한 사용자 ID로 로그인을 해서 데이터베이스를 만든다.
1 2 3
root@a5d2a69fa410:/# mysql -u qkboo -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \\g.
mysql-server 를 설치하며 만든 root 사용자 패스워드를 사용해서 데이터베이스에 접속한다.
1 2 3 4 5 6 7 8 9
$ mysql -u root -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 1 Server version: 5.6.26 MySQL Community Server (GPL)
Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
[^5]: Creating SSL & RSA Certificates and keys [^6]: [Creating SSL Certificates and keys Using openssl](6.4.3.2 Creating SSL Certificates and Keys Using openssl)