Difference between revisions of "ODBCConn/es"

From Lazarus wiki
Jump to navigationJump to search
Line 40: Line 40:
 
** SQL_GUID (TGUIDField no había sido implementado hasta recientemente).
 
** SQL_GUID (TGUIDField no había sido implementado hasta recientemente).
  
=== Why use ODBC? ===
+
=== ¿ Porque utilizar ODBC ? ===
FreePascal ships with components for connecting to several databases, such as MySQL, PostGreSQL, Firebird, Oracle, etc.
+
 
For those databases missing from the list, like MS Access, ODBC might be an outcome.
+
FreePascal se distribuye con componentes para conectar a varias bases de datos tales como MySQL, PostGreSQL, Firebird, Oracle, etc.
Actually, the TODBCConnection component was developed originally to circumvent the strict MySQL license for applications that are not GPLed or do not obey MySQL AB's [http://www.mysql.com/company/legal/licensing/foss-exception.html FLOSS exception].
+
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 [http://www.mysql.com/company/legal/licensing/foss-exception.html excepción FLOSS].
  
 
== Installing ODBC and ODBC Drivers ==
 
== Installing ODBC and ODBC Drivers ==

Revision as of 06:50, 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:

MSDN ODBC site.

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

Before you can connect to your database using ODBC, you need to install

  • an ODBC Driver Manager
  • an ODBC driver specific to the DBMS you want to connect to

The ODBC Driver Manager

Windows

Windows has an ODBC Driver Manager built in. Its configuration is controlled by

  • the Data Sources (ODBC) item under the Administrative Tools in the Control Panel (Win 2000, XP)
  • the ODBC Data Sources (32-bit) item in the Control Panel (Win 9x, ME).
  • the ODBC item in the Control Panel (Win NT)

WinXPODBCDataSourceAdministratorDrivers.png

Unices

Two popular ODBC Driver Managers for Unix-based platforms are unixODBC and iODBC. ODBCConn is known to work with unixODBC; iODBC compatibility still has to be tested.

Debian

For Debian, you can install the unixodbc package:

aptitude install unixodbc
aptitude install unixodbc-bin # if you want some GUI tools

The odbcsqldyn unit, and hence odbcconn, will search for a file called libodbc.so. It will not accept a file named like libodbc.so.1 or libodbc.so.1.0.0. Debian's unixodbc package does not create a symlink with the name /usr/lib/libodbc.so; you must either

  • create the link yourself: ln -s libodbc.so.1 /usr/lib/libodbc.so, or
  • install the unixodbc-dev package, which does create the symlink.

If you installed the unixodbc-bin package, you can run the ODBCConfig program to configure ODBC drivers and DSNs.

ODBCDataSourceAdministratorAbout.PNG

Ubuntu

For Ubuntu, follow the instruction for Debian. Note: the unixodbc-bin package might not be available from the default package repository.

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 and FILEDSN, 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 and PWD 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.