Importante

La traducción es un esfuerzo comunitario puede unirse. Esta página está actualmente traducida en |progreso de traducción|.

15.3. Lección: Añadir datos al modelo

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.

Puede ver el resultado de su acción de inserción seleccionando todos los datos en la tabla:

select * from streets;

Resultado:

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

Pruebe usted mismo: ★☆☆

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. Ponte a prueba: ★★☆

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

Ya le hemos mostrado la sintaxis para seleccionar registros. Veamos algunos ejemplos más:

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

¿Qué sucede si desea realizar un cambio en algunos datos existentes? Por ejemplo, se cambia el nombre de una calle:

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!

Una mejor solución es usar la clave principal de la tabla para hacer referencia al registro que se va a cambiar:

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';

Veamos nuestra tabla de personas ahora:

address=# select * from people;

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

15.3.7. Póngase a prueba: ★★★

Usa las habilidades que has aprendido para agregar nuevos amigos a tu base de datos:

      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. En conclusión

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. ¿Y ahora qué?

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