Importante

A tradução é um esforço comunitário você pode contribuir. Esta página está atualmente traduzida em 61.54%.

15.3. Lesson: Adding Data to the Model

Los modelos que hemos creado ahora tendrá que ser llenado con los datos que están destinados a contener.

La meta para esta lección Para aprender cómo insertar nuevos datos al modelo de base de datos.

15.3.1. Insertar sentencia

How do you add data to a table? The sql INSERT statement provides the functionality for this:

insert into streets (name) values ('High street');

Un par de cosas a tener en cuenta:

  • After the table name (streets), you list the column names that you will be populating (in this case only the name column).

  • After the values keyword, place the list of field values.

  • Las cadenas deben ser citadas utilizando comillas simples.

  • Note that we did not insert a value for the id column; 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.

Você pode ver o resultado da sua inserção selecionando todos os dados na tabela:

select * from streets;

Resultado:

select * from streets;
 id |    name
----+-------------
  1 | High street
(1 row)

Try Yourself: ★☆☆

Use the INSERT command to add a new street to the streets table.

15.3.2. Secuencia de datos Adición Según Restricciones

15.3.3. Try Yourself: ★★☆

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

Nota

Recodemos que en este ejemplo, definimos números de teléfono como cadenas y no como números enteros.

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.

También debe haber notado que:

  • No se puede añadir la calle utilizando su nombre

  • You can’t add a street using a street id before first creating the street record on the streets table

Recordar que nuestras tablas estan vinculadas por un par de llave primaria/foreana. Esto significa que ninguna persona válida puede ser creado sin que exista también un récord calle correspondiente válida.

Usar el conocimiento previo, añadir la nueva persona a la base de datos.

15.3.4. Seleccionar datos

Já mostramos a sintaxe para selecionar registros. Vejamos mais alguns exemplos:

select name from streets;
select * from streets;
select * from streets where name='Main Road';

En sesiones posteriores, vamos a entrar en más detalle sobre como seleccionar y filtrar datos.

15.3.5. Actualizar datos

E se você quiser alterar alguns dados existentes? Por exemplo, um nome de rua é alterado:

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!

Uma solução melhor é usar a chave primária da tabela para referenciar o registro a ser alterado:

update streets set name='New Main Road' where id=2;

It should return UPDATE 1.

Nota

The WHERE statement criteria are case sensitive, Main Road is not the same as Main road.

15.3.6. Eliminar datos

In order to delete an object from a table, use the DELETE command:

delete from people where name = 'Joe Smith';

Vamos ver nossa tabela de pessoas agora:

address=# select * from people;

  id | name | house_no | street_id | phone_no
 ----+------+----------+-----------+----------
(0 rows)

15.3.7. Try Yourself: ★★★

Use as habilidades que aprendeu para adicionar novos amigos ao seu banco de dados:

      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. In Conclusion

Ahora que sabe como añadir nuevos datos a los modelos existentes que se crearon previamente. Recordar que si se quiere añadir nuevos tipos de datos, es posible que se desee modificar y/o crear nuevos modelos para contener los datos.

15.3.9. What’s Next?

Ahora que se han añadido algunos datos, aprenderá cómo utilizar las consultas para acceder a estos datos de diferentes maneras.