회원가입 후 로그인
왼쪽상단의 서비스 클릭
모든 서비스 클릭
모든 서비스 보기 클릭
데이터베이스의 RDS 클릭
데이터베이스 생성 클릭
데이터베이스 옵션 설정
생성방식 : 표준생성
표준유형 : MySQL
탬플릿 : 프리티어 선택
인스턴스 구성
스토리지 구성
연결
암호인증
추가구성
최종으로 데이터베이스 생성 클릭
만들어놓은 데이터베이스 클릭
연결 및 보안 항목에서 vpc 보안그룹 클릭
보안그룹 id클릭하여 정보 페이지로 이동
인바운드 큐칙을 편집하기 위해 선택후 규칙 편집 클릭
규칙 추가 클릭하여 추가하기
다시 서비스 - DB RDS 페이지로 이동
연결 및 보안 항목에서 엔드포인트 항목 사용 예정
외부에서 원격으로 접속하기위한 코드
mysql -h "엔드포인트" -P 포트 -u 마스터 사용자 이름 -p
재시작 방법
작업에서 시작클릭
Document % mkdir sql_ws
(cd 명령어를 이용해서 문서폴더인 document로 이동후 sql_ws 폴더 만들기)
Document % cd sql_ws
(만든 폴더인 sql_ws 폴더로 경로 이동하기)
sql_ws %
(준비완료)
sql_ws % code .
(현재경로인 sql_ws에서 code . 을 입력하면 현재경로에서 vscode를 실행하라는 뜻 )
VSCode 의 sql_ws 폴더에서 새파일을 선택
생성할 파일 이름을 정하고, 파일 확장자를 sql로 입력하면 비어있는 SQL 파일이 생성됩니다.
SQL File
경찰서 정보를 테이블로 만들기
sql_ws 폴더 위치로 이동하여 zerobase 에 접속
cd sql_ws
mysql -u root -p zerobase (-p이후 한칸 띄어쓰면 데이터베이스에 직접 접속한다는 뜻)
mysql> source test01.sql (터미널에서 sql로 접속하면 mysql> 으로 변함.)
Query OK, 0 rows affected (0.05 sec) <- 완료됬다는 매시지
mysql -u username -p database < /pasth/filename.sql
( 꺽쇠 사용 안될시 아래의 문법으로 사용 가능)
cmd /c 'mysql.exe -u username -p database < filename.sql'
exit (종료하는 명령어)
서울특별시 관서별 5대 범죄 현황 정보를 테이블로 만들기
zerobase Database 에 접속하면서 SQL File 을 싱행
mysql -u root -p zerobase < test02.sql
( 꺽쇠 사용 안될시 아래의 문법으로 사용 가능)
cmd /c 'mysql.exe -u root -p zerobase < test02.sql'
mysqldump -u username -p dbname > backup.sql # 특정 데이터베이스 백업
mysqldump -u username -p dbname -r backup.sql (위방법이안된다면 이렇게 시도하면된다.)
mysqldump -u username -p --all-database > backup.sql # 모든 데이터베이스 백업
mysqldump -u root -p zerobase > zerobase.sql
(위 방법이 안되면 아래의 방법으로)
mysqldump -u root -p zerobase -r zerobase.sql
mysql -h "엔드포인트" -P 포트번호 -u username -p
zerobase Database 이동
AWS RDS(database-1) 의 zerobase Database 를 복원
source zerobase.sql;
mysqldump -u username -p dbname tablename -r backup.sql
mysqldump -u root -p zerobase celeb -r celeb.sql
mysql -h "엔드포인트" -P 포트번호 -u admin -p zerobase
...
drop table celeb; (테이블 삭제)
mysql -h "엔드포인트" -P 포트번호 -u admin -p zerobase
...
source celeb.sql;
mysqldump -d -u username -p dbname tablename > backup.sql # 특정 Table Schema Backup
mysqldump -d -u username -p dbname > backup.sql # 모든 Table Schema Backup
mysqldump -d -u root -p zerobase snl_show > snl.sql
VSCode 혹은 Web Browser 를 통해 실행하고, ds_study 환경에서 작업
실행 위치
MySQL
데이터 삭제
(시작은 터미널에서 시작 / 중간중간 오류로 변경된부분이 쪼금 있음)
mysqldump --set-gtid-purged=off -h "엔드포인트" -P 포트번호 -u admin -p zerobase polistation -r backup_police.sql
(패스워드 입력 부분)
(여기부터 mysql 시작부분)
use zerbase;
delete from police_station;
pip install mysql-connector-python
import mysql.connector
mydb = mysql.connector.connect(
host = "<hostname>",
user = "<username>",
password = "<password>"
)
import mysql.connector
local = mysql.connector.connect(
host = "localhost",
user = "root",
password = "**********"
)
remote = mysql.connector.connect(
host = "엔드포인트",
port = 3306,
user = "admin",
password = "**********"
)
import mysql.connector
local = mysql.connector.connect(
host = "<hostname>",
user = "<username>",
password = "<password>",
database = "<databasename>"
)
local.close()
import mysql.connector
mydb = mysql.connector.connect(
host = "<hostname>",
port = "<port>",
user = "<username>",
password = "<password>",
database = "<databasename>"
)
import mysql.connector
mydb = mysql.connector.connect(
host = "<hostname>",
user = "<username>",
password = "<password>",
database = "<databasename>"
)
mycursor = mydb.corsor()
mycursor.execute(<query>)
remote = mysql.connector.connect(
host = "엔드포인트",
port = "port",
user = "admin",
password = "**********",
database = "zerobase"
)
cur = remote.corsor()
cur.execute("create table sql_file (id int, filename varchar(16))")
remote.close()
remote = mysql.connector.connect(
host = "엔드포인트",
port = "port",
user = "admin",
password = "**********",
database = "zerobase"
)
cur = remote.corsor()
cur.execute("drop table sql_file")
remote.close()
import mysql.connector
mydb = mysql.connector.connect(
host = "<hostname>",
user = "<username>",
password = "<password>",
database = "<databasename>"
)
mycursor = mydb.corsor()
sql = open("<filename>.sql").read()
mycursor.execute(sql)
test03.sql 생성
test03.sql 실행
결과 확인
mydb = mysql.connector.connect(
host = "<hostname>",
user = "<username>",
password = "<password>",
database = "<databasename>"
)
mycursor = mydb.corsor()
sql = open("<filename>.sql").read()
mycursor.execute(sql, multi = True)
test04.sql 생성
test04.sql 실행(에러)
결과 확인
mycursor.execute(<query>)
result = mycursor.fetchall()
for data in result:
print(data)
sql_file 테이블 조회 (읽어올 데이터 양이 많은 경우 buffered=True)
참고, 검색결과를 Pandas 로 읽기
commit() 은 database 에 적용하기 위한 명령
결과 확인
검색결과를 Pandas 로 읽기
csv 한글이 깨지는 경우, encoding 값을 'euc-kr' 로 설정 (특히 우리나라 사이트에서 제공받은 csv 파일들.)
use zerobase;
create table tablename
(
column1 datatype not NULL,
column2 datatype not NULL,
...
constraint constraint_name
primary key (column1, column2, ...)
);
create table person
(
pid int NOT NULL,
name varchar(16),
age int,
sex char,
primary key (pid)
);
create table animal
(
name varchar(16) NOT NULL,
type varchar(16) NOT NULL,
age int,
primary key (name, type)
);
alter table tablename
drop primary key;
alter table person
drop primary key;
alter table animal
drop primary key;
alter table tablename
add primary key (column1, column2, ...);
alter table person
add primary key (pid);
alter table animal
add constraint PK_animal primary key (name, type);
# constraint PK_animal 이 부분은 생략 가능
create table tablename
(
colimn1 datatype NOT NULL,
colimn2 datatype NOT NULL,
colimn3 datatype,
colimn4 datatype,
...
constraint constraint_name
primary key (colimn1, colimn2, ...),
constraint constraint_name
foreign key (colimn3, colimn4, ...) references REF_tablename(REF_colimn)
create table orders
(
oid int NOT NULL,
order_no varchar(16),
pid int,
primary key (oid),
constraint FK_person
foreign key (pid) references person(pid)
);
create table job
(
jid int NOT NULL,
name varchar(16),
pid int,
primary key (jid),
foreign key (pid) references person(pid)
);
show create table tablename;
show create table job;
alter table tablename
drop foreign key FK_constraint;
alter table orders
drop foreign key FK_person;
alter table tablename
add foreign key (column) references REF_tablename(REF_column);
alter table orders
add foreign key (pid) references person(pid);
mysql -h "엔드포인트" -P 포트번호 -u zero -p zerobase
select count(column)
from tablename
where condition;
select count(*)
from police_station;
select count(distinct police_station)
from crime_status;
select count(distinct crime_type)
from crime_status;
select sum(column)
from tablename
where condition;
select sum(case_number)
from crime_status
where status_type = '발생';
select AVG(column)
from tablename
where condition;
select avg(case_number)
from crime_status
where crime_type like '폭력' and status_type = '검거';
select police_station, crime_type, status_type, case_number
from crime_status
where crime_type like '폭력' and status_type = '검거';
select avg(case_number)
from crime_status
where police_station like '중부' and status_type = '발생';
select police_station, crime_type, status_type, case_number
from crime_status
where crime_type like '중부' and status_type = '발생';
select MIN(column)
from tablename
where condition;
select MIN(case_number)
from crime_status
where crime_type like '강도' and status_type = '발생';
select police_station, crime_type, status_type, case_number
from crime_status
where crime_type like '강도' and status_type = '발생';
select MIN(case_number)
from crime_status
where police_station like '중부' and status_type = '검거';
select police_station, crime_type, status_type, case_number
from crime_status
where police_station like '중부' and status_type = '검거';
select MAX(column)
from tablename
where condition;
select MAX(case_number)
from crime_status
where crime_type like '살인' and status_type like '검거';
select police_station, crime_type, status_type, case_number
from crime_status
where crime_type like '살인' and status_type like '검거';
select MAX(case_number)
from crime_status
where police_station like '강남' and status_type = '발생';
select police_station, crime_type, status_type, case_number
from crime_status
where police_station like '강남' and status_type = '발생';
select column1, column2, ...
from tablename
where condition
group by column1, column2, ...
order by column1, column2, ...;
select poloce_station
from crime_status
group by poloce_station
order by poloce_station
limit 5;
select distinct poloce_station
from crime_status
limit 5;
select poloce_station, sum(case_number) 발생건수
from crime_status
where status_type like '발생'
group by poloce_station
order by 발생건수 desc
limit 5;
select poloce_station, avg(case_number) 평균검거건수
from crime_status
where status_type like '검거'
group by poloce_station
order by 평균검거건수 desc
limit 5;
select poloce_station, status_type, avg(case_number)
from crime_status
group by poloce_station, status_type
limit 6;
select column1, column2, ...
from tablename
where condition
group by column1, column2, ...
HAVING condition (Aggregate Functions)
order by column1, column2, ...;
select poloce_station, sum(case_number) count
from crime_status
where status_type like '발생'
group by poloce_station
HAVING count > 4000;
select sum(case_number)
from crime_status
where status_type like '발생' and poloce_station = '영등포';
select poloce_station, avg(case_number)
from crime_status
where (crime_type like '폭력' or crime_type like '절도') and status_type like '발생'
group by poloce_station
HAVING avg(case_number) >= 2000;
select avg(case_number)
from crime_status
where (crime_type like '폭력' or crime_type like '절도') and status_type like '발생' and poloce_station like '영등포';
select *
from crime_status
where (crime_type like '폭력' or crime_type like '절도') and status_type like '발생' and poloce_station like '영등포';
실습환경은 AWS 에서 시작
데이터 확인
select ucase(string);
select ucase('This Is ucase Test.');
select ucase(menu)
from sandwich
where price > 15;
select lcase(string);
select lcase('This Is LCASE Test.');
select lcase(menu)
from sandwich
where price < 5;
select mid(string, start_position, lenth);
select mid('This is mid test.', 1, 4);
select mid('This is mid test.', 6, 5);
select mid('This is mid test.', -4, 4);
select mid('This is mid test.', -8, 3);
select mid(cafe, 6, 4)
from sandwich
where ranking = 11;
select length(string);
select length('This is len test.');
select length('');
select length(' ');
select length('NULL');
select length('address'), address
from sandwich
where ranking <= 3;
select round(number, decimals_place);
select round(315.625);
select round(315.625, 0);
select round(315.625, 1);
select round(315.625, 2);
select round(315.625, -1);
select round(315.625, -2);
select ranking, price, round(price)
from sandwich
order by ranking desc
limit 3;
select now();
select now();
select format(number, decimals_place);
select format(12345.6789, 0);
select format(12345.6789, 2);
select format(12345.6789, 10);
select format(가격, 0)
from oil_price
where round(가격, -3) >= 2000;
select format(12345.6789, 0);
select column1, (select column2 from table2 where condition)
from table1
where condition;
select case_number,
(select avg(case_number)
from crime_status
where crime_type like '강도' and status_type like '검거') avg
from crime_status
where police_station like '은평' and crime_type like '강도' and status_type like '검거';
select a.column, b.column
from table a, (select colmun1, colmun2 from table2) b
where condition;
select c.police_station, c.crime_type, c.case_number
from crime_status c,
(select police_station, max(case_number) count
from crime_status
where status_type like '발생'
group by police_station) m
where c.police_station = m.police_station
and c.case_number = m.count;
select column_names
from table_name
where column_names = (select column_name
from table_name
where condition)
order by column_name;
select name
from celeb
where name = (select host
from snl_show
where id = 1);
select column_names
from table_name
where column_names IN (select column_name
from table_name
where condition)
order by column_name;
select host
from snl_show
where host in (select name
from celeb
where job_title like '%영화배우%');
select column_names
from table_name
where exists (select column_name
from table_name
where condition)
order by column_names;
select name
from police_station p
where exists (select police_station
from crime_status c
where p.name = c.reference and case_number > 2000);
select column_names
from table_name
where column_name = ANY (select column_name
from table_name
where condition)
order by column_names;
select name
from celeb
where name = ANY (select host
from snl_show);
select column_names
from table_name
where column_name = ALL (select column_name
from table_name
where condition)
order by column_names;
select name
from celeb
where name = ALL (select host
from snl_show
where id = 1);
select column_names
from tablename a
where (a.column1, a.column2, ...) IN (select b.column1, b.column2, ...
from tablename b
where a.column_name = b.column_name)
order by column_names;
select name, sex, agency
from celeb
where (sex, agency) in (select sex, agency
from celeb
where name = '강동원');