중요
번역은 여러분이 참여할 수 있는 커뮤니티 활동입니다. 이 페이지는 현재 73.08% 번역되었습니다.
15.3. 수업: 모델에 데이터 추가하기
이제 우리가 생성한 모델을, 원래 담으려던 데이터로 채워야 합니다.
이 수업의 목표: 데이터베이스 모델에 새 데이터를 삽입하는 방법을 배우기.
15.3.1. 삽입 선언문
How do you add data to a table? The sql INSERT statement provides the
functionality for this:
insert into streets (name) values ('High street');
다음 사항을 기억하십시오:
After the table name (
streets), you list the column names that you will be populating (in this case only thenamecolumn).After the
valueskeyword, place the list of field values.문자열은 작은따옴표로 감싸야 합니다.
Note that we did not insert a value for the
idcolumn; this is because it is a sequence and will be auto-generated.If you do manually set the
id, you may cause serious problems with the integrity of your database.
You should see INSERT 0 1 if it is successful.
테이블의 모든 데이터를 선택하면 삽입 선언문의 결과를 볼 수 있습니다:
select * from streets;
결과:
select * from streets;
id | name
----+-------------
1 | High street
(1 row)
혼자서 해보세요: ★☆☆
Use the INSERT command to add a new street to the streets table.
해답
여러분이 사용해야 할 SQL 명령어는 다음과 같습니다(도로 이름을 여러분이 선택한 이름으로 대체할 수 있습니다):
insert into streets (name) values ('Low Road');
15.3.2. 제약 조건에 따라 데이터를 연속 추가하기
15.3.3. 혼자서 해보세요: ★★☆
Try to add a person object to the people table with the following details:
Name: Joe Smith
House Number: 55
Street: Main Street
Phone: 072 882 33 21
참고
이 예제에서 전화번호를 정수가 아니라 문자열로 정의한 것을 기억하십니까?
At this point, you should have an error report if you try to do this without
first creating a record for Main Street in the streets table.
다음 사항에 대해서도 알게 됐을 것입니다:
도로 이름으로는 추가할 수 없습니다.
You can’t add a street using a street
idbefore first creating the street record on thestreetstable
여러분의 두 테이블이 기본 키/외래 키 쌍으로 연결되어 있다는 사실을 기억하십시오. 다시 말해 상응하는 무결한 도로 레코드 없이는 무결한 사람 레코드를 생성할 수 없다는 뜻입니다.
이런 지식을 사용해서 데이터베이스에 새 인물을 추가해보십시오.
해답
올바른 SQL 선언문은 다음과 같습니다:
insert into streets (name) values('Main Road');
insert into people (name,house_no, street_id, phone_no)
values ('Joe Smith',55,2,'072 882 33 21');
‘streets’ 테이블을 (이전과 마찬가지로 ‘select’ 선언문을 사용해서) 다시 살펴보면 Main Road 항목의 id 가 2 라는 사실을 알 수 있을 겁니다.
이것이 앞의 선언문에 2 라는 숫자를 그냥 입력해도 되었던 이유입니다. 앞의 선언문에서 Main Road 를 온전히 입력하지 않았더라도, 데이터베이스가 street_id 값 2 와 연결할 것이기 때문입니다.
새 도로 객체를 이미 추가했다면, 새 Main Road 의 id 가 2 가 아니라 3 일 수도 있습니다.
15.3.4. 데이터 선택하기
앞에서 데이터를 선택할 수 있는 문법을 배웠습니다. 몇 가지 예를 더 들어보겠습니다:
select name from streets;
select * from streets;
select * from streets where name='Main Road';
다음 절들에서 데이터를 선택하고 필터링하는 방법에 대해 더 자세히 알아볼 것입니다.
15.3.5. 데이터 업데이트하기
어떤 기존 데이터를 변경하고자 할 경우 어떻게 해야 할까요? 예를 들어 도로 이름이 변경됐다고 해봅시다:
update streets set name='New Main Road' where name='Main Road';
Be very careful using such update statements - if more than one record matches
your WHERE clause, they will all be updated!
다음과 같이 변경할 레코드를 참조하는 테이블 기본 키를 사용하는 방법이 더 낫습니다:
update streets set name='New Main Road' where id=2;
It should return UPDATE 1.
참고
The WHERE statement criteria are case sensitive, Main
Road is not the same as Main road.
15.3.6. 데이터 삭제하기
In order to delete an object from a table, use the DELETE command:
delete from people where name = 'Joe Smith';
‘people’ 테이블이 어떻게 변경됐는지 살펴봅시다:
address=# select * from people;
id | name | house_no | street_id | phone_no
----+------+----------+-----------+----------
(0 rows)
15.3.7. 혼자서 해보세요: ★★★
지금까지 배운 기술을 이용해서 여러분의 데이터베이스에 새 친구들 몇 명을 추가해보십시오:
name | house_no | street_id | phone_no
-----------------+----------+-----------+--------------
Joe Bloggs | 3 | 2 | 072 887 23 45
Jane Smith | 55 | 3 | 072 837 33 35
Roger Jones | 33 | 1 | 072 832 31 38
Sally Norman | 83 | 1 | 072 932 31 32
15.3.8. 결론
이제 이전 단계에서 생성했던 기존 모델에 새 데이터를 추가하는 방법을 배웠습니다. 새로운 유형의 데이터를 추가하려면 기존 모델을 수정하거나, 해당 데이터를 담을 수 있는 새 모델을 생성해야 할 수도 있다는 사실을 기억하십시오.
15.3.9. 다음은 무엇을 배우게 될까요?
이제 데이터를 추가했으니, 쿼리를 통해 이 데이터에 다양한 방식으로 접근하는 방법에 대해 배워보겠습니다.