Working With TSQLQuery/es
│
English (en) │
español (es) │
français (fr) │
日本語 (ja) │
polski (pl) │
中文(中国大陆) (zh_CN) │
Para una referencia general de cómo trabajar con Bases de Datos ver Bases de Datos en Lazarus
Trabajando con TSQLQuery
El conjunto de datos (DataSet) que devuelve TSQLQuery se puede ver con una instancia de TDBGrid, pero no es muy recomendable para editar los campos de los registros individuales. Para realizar esto en conveniente poner varios componentes ligados a datos para registros individuales, cómo TDBEdit en el formulario, y poner su propiedad DataSource con el valor de nombre de la fuente de datos utilizada. En la propiedad DataField seleccionaremos el nombre del campo (v.gr. 'IDENTIDAD') o una expresión que resulte en una cadena aceptable.
Si añadimos un componente de navegación TDBNavigator resultará muy fácil moverse por los registros y seleccionarlos para editarlos. Cuándo un registro es seleccionado mediante un TDBNavigator o moviendo el cursor en el DBGrid los datos correspondientes del registro se mostrarán en el TDBEdity si se pulsa el botón de Editar , su contenido puede ser modificado. Con el botón Post podemos confirmar la edición o bien desechar los cambios con Cancelar .
En general el proceso es el siguiente:
- Sitúa un componente TSQLQuery en el formulario o móulo de datos, da los valores adecuados a las propiedadesDatabase, Transaction y SQL.
- Sitúa un componente TDatasource component, haz que su propiedad Dataset apunte a la instancia de TSQLQuery.
- Sitúa un componente TDBGrid en el formulario selecciona en su propiedad Datasource el nombre dado al componente TDatasource anterior.
- Opcionalmente sitúa un componente TDBNavigator y da valor a su propiedad Datasource para usar el TDatasource.
Tras esto poner la propiedad Active a verdadero (True), y podremos ver los datos suministrados por la consulta.
Los componentes TSQLConnection y TSQLTransaction, que también hemos puesto en el formulario, tienen su propiedad Active a verdadera.
Actualización de datos
Si es necesario poder Borrar o modificar registros, la Base de datos tiene que
- Tener una columna con la Clave Primaria.
- Tener un conjunto de campos que individualicen cada registro, que normalmente serán parte del índice único. Este índice no es imprescindible, pero contribuirá a que las consultas sean más rápidas.
Si no existen ni el campo primario ni esos campos que individualizan un registro será necesario añadir un registro de clave primaria. Esto se realiza preferiblemente al diseñar la estructura de la tabla en el momento de crearla, pero podemos añadirla posteriormente.
El siguiente código en un cliente MySQL, por ejemplo, añadirá un índice único para su tabla. <delphi> alter table ejemplo1
add column autoidentificador int primary key auto_increment;</delphi>
La adición del campo no estropeará nada y permitirá a tus aplicaciones para actualizarlo.
Cambios diferidos (cached)
El componente TSQLQuery guarda los cambios en un espacio de memoria intermedia. Es decir, los cambios no son enviados inmediatamente a la Base de datos, sino que se mantienen en memoria hasta que llamamos al método ApplyUpdates. En ese momento los cambios se transforman en sentencias DML de SQL, y son aplicadas a la Base de datos. Si no se utiliza el método ApplyUpdates, la Base de datos no será actualizada con los cambios locales realizados.
Primary key fields
When updating records, TSQLQuery needs to know which fields comprise the primary key that can be used to update the record, and which fields should be updated: based on that information, it constructs an SQL UPDATE, INSERT or DELETE command.
The construction of the SQL statement is controlled by the UsePrimaryKeyAsKey property and the ProviderFlags properties.
The Providerflags property is a set of 3 flags:
- pfInkey
- The field is part of the primary key
- pfInWhere
- The field should be used in the WHERE clause of SQL statements.
- pfInUpdate
- Updates or inserts should include this field.
By default, ProviderFlags consists of pfInUpdate only.
If your table has a primary key (as described above) then you only need to set the UsePrimaryKeyAsKey property to True and everything will be done for you. This will set the pfInKey flag for the primary key fields.
If the table doesn't have a primary key index, but does have some fields that can be used to uniquely identify the record, then you can include the pfInKey option in the ProviderFlags property all the fields that uniquely determine the record.
The UpdateMode property will then determine which fields exactly will be used in the WHERE clause:
- upWhereKeyOnly
- When TSQLQuery needs to construct a WHERE clause for the update, it will collect all fields that have the pfInKey flag in their ProviderFlags property set, and will use the values to construct a WHERE clause which uniquely determines the record to update -- normally this is only needed for an UPDATE or DELETE statement.
- upWhereChanged
- In addition to the fields that have pfInKey in the ProviderFlags property, all fields that have pfInWhere in their ProviderFlags and that have changed, will also be included in the WHERE clause.
- upWhereAll
- In addition to the fields that have pfInKey in the ProviderFlags property, all fields that have pfInWhere in their ProviderFlags, will also be included in the WHERE clause.
Controlling the update
It is possible to specify which fields should be updated: As mentioned above: Only fields that have pfInUpdate in their ProviderOptions property will be included in the SQL UPDATE or INSERT statements. By default, pfInUpdate is always included in the ProviderOptions property.