Difference between revisions of "ODBCConn/es"
Line 62: | Line 62: | ||
* El elemento ''Orígenes de datos (32-bit)'' que se encuentra en el ''Panel de control'' (Win 9x, ME). | * El elemento ''Orígenes de datos (32-bit)'' que se encuentra en el ''Panel de control'' (Win 9x, ME). | ||
* El elemento ''ODBC'' en el ''Control Panel'' (Win NT) | * El elemento ''ODBC'' en el ''Control Panel'' (Win NT) | ||
+ | |||
[[Image:WinXPODBCDataSourceAdministratorDrivers.png]] | [[Image:WinXPODBCDataSourceAdministratorDrivers.png]] |
Revision as of 07:17, 9 April 2009
│
English (en) │
español (es) │
français (fr) │
日本語 (ja) │
La unit ODBCConn implementa una conexión SQLdb con fuentes de datos ODBC.
Overview
ODBC
ODBC (Open Database Connectivity) o conectividad abierta de base de datos es una tecnología que permite conectar a una gran variedad de bases de datos utilizando una sola API, en concreto la API ODBC.
Existen implementaciones ODBC para distintas plataformas estando disponibles los drivers para la mayoría de los sistemas de gestión de bases de datos actuales. La documentación oficial sobre ODBC se puede encontrar en la siguiente dirección:
TOBCConnection
FreePascal se distribuye con las cabeceras (headers) ODBC; encontrándose en las unidades odbcsql
y odbcsqldyn
.
TODBCConnection
es un descendiente de TSQLConnection
que aporta unn agradable OOPP wrapper para ODBC utilizando el framework SQLdb.
En Lazarus se puede encontrar el componente TODBCConnection
en la solapa SQLdb.
También se puede utilizar el componente TODBCConnection
añadiendo ODBCConn
en la clausula uses.
Se han implementado las siguientes características:
- Ejecutar consultas (queries) y recabar cojuntos de resultados.
- La mayor parte de tipos de campos, incluyendo blobs.
- query parameters (tipos string (cadena) e integer (entero)).
- Preparando consultas (queries).
- UpdateIndexDefs (lo que permite utilizar ApplyUpdates); parche remitido a fpc-devel, May 2, 2007.
Otras implementaciones están pendientes y son:
- Soporte de transacción adecuada; actualmente cada conexión corresponde a una transacción.
- Algunos tipos de campo.
- SQL_TYPE_UTC* (están mencionados en la documentación sobre ODBC , pero parece que no se están utilizando en la implementación).
- SQL_INTERVAL_* (¿Que debería corresponder con TFieldType?).
- SQL_GUID (TGUIDField no había sido implementado hasta recientemente).
¿ Porque utilizar ODBC ?
FreePascal se distribuye con componentes para conectar a varias bases de datos tales como MySQL, PostGreSQL, Firebird, Oracle, etc. Para aquellas bases de datos que no figuran en la lista, tales como MS-Access, ODBC es una buena opción. Actualmente, el componente TODBCConnection está diseñado para esquivar (circumvent) la estricta licencia de MySQL para aplicaciones que no sean GPL o que no cumplan con MySQL AB's excepción FLOSS.
Installing ODBC and ODBC Drivers
Antes de poder conectar a una base de datos utilizando ODBC, es necesario instalar primero:
- Un gestor de drivers ODBC (Driver Manager).
- Un driver ODBC específico para la DBMS a la cual se va a conectar.
The ODBC Driver Manager
Windows
Windows contiene un gestor de drivers ODBC que podemos utilizar para realizar configuraciones con cierta facilidad y que se puede encontrar en las siguientes ubicaciones dependiendo del sistema operativo:
- El elemento Orígenes de datos (ODBC) que se encuentra en Herramientas administrativas dentro del Panel de control (Win 2000, XP, Vista).
- El elemento Orígenes de datos (32-bit) que se encuentra en el Panel de control (Win 9x, ME).
- El elemento ODBC en el Control Panel (Win NT)
Unices
Dos gestores de drivers ODBC muy conocidos para plataformas de tipo UNIX son unixODBC y iODBC.
TODBCConn
es conocido por funcionar con unixODBC; su compatibilidad con iODBC está todavía pendiente de verificación.
Debian
Para Debian se puede instalar el paquete unixodbc mediante los siguientes mandatos:
aptitude install unixodbc aptitude install unixodbc-bin # si necesitas algunas utilidades GUI (Interface gráfica de usuario)
La unidad odbcsqldyn
, y por tanto odbcconn
, buscarán un fichero llamado libodbc.so
.
No aceptará un fichero del estilo libodbc.so.1
o libodbc.so.1.0.0
.
El paquete unixodbc de debian no crea un enlace simbólico (symlink) con el nombre /usr/lib/libodbc.so
; por lo que el usuario deberá:
- Crear el enlace manualmente:
ln -s libodbc.so.1 /usr/lib/libodbc.so
, o bien - Instalar el paquete unixodbc-dev, el cual si creará el enlace.
Si se tiene instalado el paquete unixodbc-bin entonces se puede arrancar el programa ODBCConfig
para configurar los drivers ODBC y los DSN.
Ubuntu
Para Ubuntu, seguir las instrucciones para Debian.
Nota: el paquete unixodbc-bin puede no estar disponible desde el repositorio por defecto de paquetes.
ODBC Drivers
TODO
Connecting to an ODBC data source
The parameters for connecting to an ODBC data source are described in a connection string.
This is a string of the form NAME=VALUE;NAME=VALUE
.
TODBCConnection
provides a wrapper around this connection string.
Some of its properties are mapped to name-value pairs in the connection string, and custom parameters can be specified in the Params
property (which is a TStrings
).
The ODBC connection string
Before going to the details of this wrapper, you must first have a basic understanding of how an ODBC data source is identified. First of all, an ODBC driver manager provides two ways to make a shortcut for a set of parameters:
- DSN (DataSource Name): a system or user defined data source, identified by a (unique) name. DSNs can be configured using the ODBC Data Source Administrator or by manually editing the
odbc.ini
file (or registry). - File DSN: a file which contains connection parameters. An ODBC Data Source Administrator usually allows you to create File DSNs from the GUI.
The parameters in a DSN or File DSN can always be combined with additional parameters in the connection string, for example to specify a password.
The ODBC specification defines a few parameters that can be used in a connection string:
- Two special parameters,
DSN
andFILEDSN
, allow one to select a set of pre-defined parameters, as described above. - The
DRIVER
specifies which ODBC driver to use. Obviously, this is a very important parameter. - The
UID
andPWD
parameters are used to supply a username and password.
All other parameters are driver dependent. Please refer to the documentation of the specific driver to learn more about available parameters and their names!
TODBCConnection properties
The following table describes the mapping to TODBCConnection
properties to ODBC connection string parameters:
Property | Type | Connection string parameter |
---|---|---|
Driver |
string |
DRIVER
|
DatabaseName |
string |
DSN , not to something like DATABASENAME , which is not part of the ODBC standard
|
FileDSN |
string |
FILEDSN
|
Password |
string |
PWD
|
UserName |
string |
UID
|
HostName |
string |
none; there is no corresponding parameter in the ODBC standard |
Params |
TStrings |
Use this to specify custom parameters. Each item must be of the form NAME=VALUE .
|
Note that TODBCConnection
will take care of escaping parameter values in the connection string (when required).
The LoginPrompt
boolean property is not implemented yet.
It would require finding the correct window handle, so a driver can show a GUI dialog to specify parameters.
Note that this is not controlled by the connection string, but rather by the last parameter to the ODBC API function SQLDriverConnect
.
Examples
In this section, examples are given of connecting to certain DBMSs using their specific ODBC drivers. The syntax used in the examples is as in *.lfm files. It should be straight-forward to interpret them.
Connecting to MySQL
For a reference of supported parameters by the MyODBC driver, see [1].
The driver name differs a bit depending on the platform and MyODBC version; examples are:
Driver = 'MySQL' (Unix) Driver = 'MySQL ODBC 3.51 Driver' (Windows) Driver = 'MySQL Connector/ODBC v5' (Windows)
Other parameters:
UserName = 'myUsername' Password = 'myPassword' Params.Strings = ( 'SERVER=example.com', 'PORT=3306', 'DATABASE=myDatabase' )
Connecting to MS Access
On Windows, you can use
Driver = 'Microsoft Access Driver (*.mdb)' Params.Strings = ( 'DBQ=C:\path\to\my\database.mdb' )
Note: The MS Access ODBC driver seems not to support the SQLPrimaryKeys
API function, hence UpdateIndexDefs
will fail.
Currently, you must set SQLQuery.ReadOnly:=true;
to avoid an exception until code has been added that tests for the availability of the function in the driver.
Debugging ODBC
There are several facilities in ODBC that are helpful when debugging your ODBC application.
Error Messages
Each ODBC API call also returns a succes code; if there is an error, more information can be retrieved using calls to SQLGetDiagRec
. (For the sake of completeness: diagnostic records are also available when an API call returns SQL_SUCCES_WITH_INFO
.)
TODBCConnection
checks the return code of each ODBC call and contructs an EODBCException
.
The message
of this exception consists of:
- a message identifying what the
TODBCConnection
was doing when the error occurred - the return code of the ODBC API call (e.g.
SQL_ERROR
) - a number of diagnostic records (obtained using
SQLGetDiagRec
); each record consists of three fields:- a 5-character error code identifying the error
- a 'native error code'
- a message describing the error
Note: if you get a 'Function sequence error' in the finalization section of the ODBCConn
unit, then you probably did not properly clean up all you queries and connections.
Tracing
Most ODBC managers have a tracing option in which all ODBC API calls are logged to a trace log. This can be very useful for debugging an ODBC application. The ODBC Data Source Administration GUI of both Windows and unixODBC have a tab where you can configure the tracing option.
Of course the trace log is mainly useful for developers that are familiar with the ODBC API, but it can help to identify the problem. Also, you can attach a trace log if you report a problem to the bug tracker.