Версия для печати

Архив документации на OpenNet.ru / Раздел "Базы данных, SQL" (Многостраничная версия)

MySQL: Руководство по ODBC и MyODBC

Версия 1.0

Автор: Алексей Паутов.

Источник: RussianLDP:MySQL


Приложение 1. Переменные окружения

Имеется список всех системных переменных, которые используются MySQL непосредственно или косвенно. Большинство их также может быть найдено в других местах в этом руководстве.

Обратите внимание, что любые параметры в командной строке будут иметь приоритет над значениями, определенными в файлах конфигурации и системных переменных, а значения в файлах конфигурации всегда имеют приоритет над значениями в системных переменных.

Во многих случаях предпочтительно использовать файл выбора конфигурации вместо системных переменных, чтобы изменить поведение MySQL. Подробности в разделе "4.11 Файл опций my.cnf".

DBI_USERЗаданный по умолчанию пользователь для интерфейса Perl DBI.
DBI_TRACEИспользуется при трассировке Perl DBI.
HOMEЗаданный по умолчанию путь для файла хронологии mysql, обычно $HOME/.mysql_history.
LD_RUN_PATHИспользуется, чтобы определить, где находится Ваша библиотека libmysqlclient.so.
MYSQL_DEBUGОпции трассировки при отладке.
MYSQL_HISTFILEПуть к файлу хронологии mysql.
MYSQL_HOSTЗаданное по умолчанию имя хоста, используемое подсказкой командной строки mysql.
MYSQL_PWDЗаданный по умолчанию пароль при соединении с mysqld. Обратите внимание, что использование этой возможности задания пароля опасно!
MYSQL_TCP_PORTЗаданный по умолчанию порт TCP/IP.
MYSQL_UNIX_PORTСокет по умолчанию. Используется для связи с localhost.
PATHИспользуется оболочкой для поиска программ и утилит пакета MySQL.
TMPDIRКаталог, где будут созданы временные таблицы или файлы.
TZЭто должно быть установлено к Вашей зоне местного времени. Подробности в разделе "11.4.6 Проблемы часового пояса".
UMASK_DIRСоздание каталога пользователя будет выполнено с данной маской прав доступа. Обратите внимание, что это значение будет использовано в операции AND с UMASK!
UMASKТо же самое, но для создания файлов.
USERЗаданный по умолчанию пользователь в Windows, чтобы использовать при соединении с mysqld.

Приложение 2. GNU GENERAL PUBLIC LICENSE

Version 2, June 1991

Copyright © 1989, 1991 Free Software Foundation, Inc.
59 Temple Place - Suite 330, Boston, MA  02111-1307, USA

Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.

Preamble

The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too.

When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.

To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.

For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.

We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.

Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.

Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.

The precise terms and conditions for copying, distribution and modification follow.

2 TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  1. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The ``Program'', below, refers to any such program or work, and a ``work based on the Program'' means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term ``modification''.) Each licensee is addressed as ``you''. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
  2. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
  3. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
    1. You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
    2. You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
    3. If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
    These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
  4. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
    1. Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
    2. Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
    3. Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
    The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
  5. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
  6. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
  7. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
  8. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
  9. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
  10. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and ``any later version'', you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
  11. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.

    9.4 NO WARRANTY

  12. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
  13. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

9.5 END OF TERMS AND CONDITIONS

3 How to Apply These Terms to Your New Programs

If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.

To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the ``copyright'' line and a pointer to where the full notice is found.

one line to give the program's name and a brief idea of what it does.

Copyright (C) yyyy name of author

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

Also add information on how to contact you by electronic and paper mail.

If the program is interactive, make it output a short notice like this when it starts in an interactive mode:

Gnomovision version 69, Copyright (C) 19yy name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.

The hypothetical commands show w and show c should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than show w and show c; they could even be mouse-clicks or menu items--whatever suits your program.

You should also get your employer (if you work as a programmer) or your school, if any, to sign a ``copyright disclaimer'' for the program, if necessary. Here is a sample; alter the names:

Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.

signature of Ty Coon, 1 April 1989
Ty Coon, President of Vice

This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License.


Приложение 3. GNU LESSER GENERAL PUBLIC LICENSE

Version 2.1, February 1999

Copyright © 1991, 1999 Free Software Foundation, Inc.
59 Temple Place -- Suite 330, Boston, MA 02111-1307, USA

Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.

[This is the first released version of the Lesser GPL.  It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]

1 Preamble

The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users.

This license, the Lesser General Public License, applies to some specially designated software--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below.

When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things.

To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it.

For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights.

We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library.

To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others.

Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license.

Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs.

When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library.

We call this license the Lesser General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances.

For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License.

In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system.

Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library.

The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a ``work based on the library'' and a ``work that uses the library''. The former contains code derived from the library, whereas the latter must be combined with the library in order to run.

2 TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  1. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called ``this License''). Each licensee is addressed as ``you''. A ``library'' means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The ``Library'', below, refers to any such software library or work which has been distributed under these terms. A ``work based on the Library'' means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term ``modification''.) ``Source code'' for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does.
  2. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
  3. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
    1. The modified work must itself be a software library.
    2. You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change.
    3. You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License.
    4. If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.)
    These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
  4. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library.
  5. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code.
  6. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a ``work that uses the Library''. Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a ``work that uses the Library'' with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a ``work that uses the library''. The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a ``work that uses the Library'' uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself.
  7. As an exception to the Sections above, you may also combine or link a ``work that uses the Library'' with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things:
    1. Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable ``work that uses the Library'', as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.)
    2. Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with.
    3. Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution.
    4. If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place.
    5. Verify that the user has already received a copy of these materials or that you have already sent this user a copy.
    For an executable, the required form of the ``work that uses the Library'' must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute.
  8. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things:
    1. Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above.
    2. Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.
  9. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
  10. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it.
  11. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License.
  12. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
  13. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
  14. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and ``any later version'', you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation.
  15. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.

    9.6 NO WARRANTY

  16. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
  17. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

9.7 END OF TERMS AND CONDITIONS

3 How to Apply These Terms to Your New Libraries

If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License).

To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the ``copyright'' line and a pointer to where the full notice is found.

one line to give the library's name and an idea of what it does.
Copyright (C) year name of author

This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or (at
your option) any later version.

This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

Also add information on how to contact you by electronic and paper mail.

You should also get your employer (if you work as a programmer) or your school, if any, to sign a ``copyright disclaimer'' for the library, if necessary. Here is a sample; alter the names:

Yoyodyne, Inc., hereby disclaims all copyright interest in the library
`Frob' (a library for tweaking knobs) written by James Random Hacker.

signature of Ty Coon, 1 April 1990
Ty Coon, President of Vice

That's all there is to it!


MySQL: Руководство по ODBC и MyODBC

Версия 1.0. 20 апреля 2004 г.

Автор: Алексей Паутов. Данный документ подготовлен в рамках некоммерческого проекта RussianLDP:MySQL ( http://www.botik.ru/~rldp/mysql.htm).


2 Общая информация относительно ODBC и MyODBC 3.51

Эта глава содержит общую информацию относительно ODBC и MyODBC.

2.1 Введение в ODBC

Open Database Connectivity (ODBC) представляет собой интерфейс прикладной программы (API) для доступа к базам данных. Это основано на спецификациях Call-Level Interface (CLI) от X/Open и ISO/IEC для API баз данных. Как язык доступа к базам данных применяется Structured Query Language (SQL).

ODBC разработан для максимальной способности к взаимодействию, то есть одна прикладная программа может без изменения своего исходного текста работать через интерфейс с какой угодно СУБД. Прикладные программы вызывают функции интерфейса ODBC, которые выполнены в специфических для базы данных модулях, названных драйверами. Использование драйверов изолирует прикладные программы от специфических для базы данных обращений. Подробнее об этом можно почитать на http://www.microsoft.com/data.

2.2 Что такое ODBC

Первое и главное: ODBC является спецификацией для API базы данных. Этот API независим от любой СУБД, операционной системы или языка программирования.

ODBC API основан на спецификациях CLI от X/Open и ISO/IEC. ODBC 3.x полностью соответствует обоим этим спецификациям, более ранние версии ODBC были основаны на предварительных версиях этих спецификаций, но полностью не выполняли их, зато добавили свойства, нужные только разработчикам оконных приложений, например, прокручиваемые курсоры.

Разработчики драйверов для СУБД выполняют функции ODBC API. Приложения вызывают функции в этих драйверах, чтобы обратиться к данным способом, независимым от базы данных. Администратор драйверов (Driver Manager) управляет связью между прикладными программами и драйверами.

2.3 Как ODBC стандартизирует доступ к базе данных

Имеются два архитектурных требования:

  1. Прикладные программы должны быть способны обратиться ко многим СУБД, используя тот же самый исходный текст без того, чтобы его перетранслировать или заново компоновать.
  2. Прикладные программы должны быть способны обратиться ко многим СУБД одновременно (через разные драйверы).

ODBC успешно решает эти проблемы следующим способом:

ODBC является интерфейсом уровня вызовов:
Чтобы решить проблему с тем, как прикладные программы обращаются ко многим СУБД, используя один и тот же исходный текст, существует стандарт CLI. ODBC содержит все функции в спецификации CLI и обеспечивает дополнительные функции, обычно требуемые прикладными программами.
ODBC определяет стандартный синтаксис SQL:
В дополнение к стандартному интерфейсу уровня обращения (вызова), ODBC определяет стандартный синтаксис SQL. Он базируется на спецификации X/Open SQL CAE. Если используемый ODBC синтаксис отличается от того, который применяет конкретная СУБД, производится преобразование на лету. Однако, такие преобразования редки потому, что большинство СУБД уже используют стандартный синтаксис языка SQL.
ODBC предоставляет Driver Manager для управления одновременным доступом к многим СУБД:
Хотя использование драйверов решает проблему одновременного доступа ко многим базам данных, код, необходимый, чтобы сделать это, может быть сложен. Прикладные программы которые разработаны, чтобы работать со всеми драйверами, не могут быть статически связаны с любыми драйверами. Вместо этого они должны загрузить драйверы во время выполнения и вызывать функции в них через таблицу указателей функций. Ситуация становится более сложной, если прикладная программа использует много драйверов сразу. Чтобы избавить программу от проблем с этим, ODBC обеспечивает Driver Manager. Администратор драйверов (Driver Manager) осуществляет все функции ODBC обычно как вызовы функций ODBC в драйверах и статически связан с прикладной программой или загружен прикладной программой во время выполнения. Таким образом, вызовы из прикладной программы функций ODBC по именам обрабатываются в Driver Manager вместо того, чтобы обращаться по указателю к каждому драйверу. ODBC предоставляет много возможностей СУБД, но не требует, чтобы каждый драйвер поддерживал их все.

2.4 Архитектура (My)ODBC

Архитектура MyODBC имеет 5 главных компонентов как показано ниже:

Приложение:
Это программа, которая вызывает ODBC API, чтобы обратиться к данным с сервера (MySQL). Прикладная программа общается с администратором драйверов или драйвером, непосредственно использующим стандарт ODBC-обращения. Прикладная программа не заботится, где данные сохранены, как они сохранены или как система конфигурирована, чтобы обратиться к данным. Единственное, что реально надо знать, имя источника данных (Data Source Name, DSN). Ряд задач является общим для всех программ, независимо от того, как они используют ODBC. Эти задачи: Самыми главными тут являются передача на рассмотрение инструкции SQL для выполнения и получение результатов запроса (если они есть).
Driver manager:
Driver Manager представляет собой библиотеку, которая управляет связью между прикладной программой и драйвером или драйверами. Это делает:
Драйвер MyODBC:
Драйвер MyODBC представляет собой библиотеку, которая осуществляет функции в ODBC API. Это обрабатывает ODBC-обращения к функции, представляет на рассмотрение запросы SQL на сервер MySQL и возвращает результаты обратно прикладной программе. В случае необходимости, драйвер изменяет запрос прикладной программы так, чтобы запрос соответствовал синтаксису MySQL.
ODBC.INI:
ODBC.INI является главным файлом настройки ODBC, который хранит драйвер и информацию о базе данных, требуемую, чтобы соединиться с сервером. Это используется Driver Manager, чтобы определить который драйвер надо загрузить, используя Data Source Name. Драйвер использует этот файл, чтобы прочитать параметры подключения, основанные на определенном DSN. Для получения большего количества информации прочтите раздел "3.2 Настройка MyODBC DSN".
MySQL SERVER:
Это источник данных.

2.5 Типы ODBC-драйверов MySQL

Как описано ранее, MySQL AB поддерживает два драйвера ODBC с открытыми исходными текстами, а именно MyODBC и MySQL ODBC 3.51, для работы с MySQL через ODBC API.

2.6 Где взять MyODBC

MySQL AB распространяет все свои программы под General Public License (GPL). Самую свежую версию MyODBC или MyODBC 3.51 (двоичные коды и исходные тексты) можно скачать с http://www.mysql.com. Подробно о MySQL ODBC рассказано на http://www.mysql.com/downloads/api-myodbc.html.

2.7 Как инсталлировать MyODBC

2.7.1 Двоичная версия на Windows

Для установки MyODBC на Windows Вы должны скачать соответствующий дистрибутивный файл для Вашей операционной системы с http://www.mysql.com/downloads/api-myodbc.html, распаковать его и выполнить файл SETUP.EXE.

2.7.2 Установка из исходных текстов под Windows

2.7.2.1 Требования

2.7.2.2 Построение MyODBC 3.51

MyODBC 3.51 поставляется в виде исходников с Makefile, который использует nmake. В дистрибутиве есть WIN_Makefile для формирования нормальной версии и WIN_Makefile_debug для формирования отладочной версии драйвера и DLL-библиотек. Для построения драйвера:

Скачайте исходники и распакуйте их в какой-нибудь каталог, скажем, myodbc3-src. Дальше выполните следующие команды для создания нормальной версии:

Command> cd myodbc3-src
Command> nmake -f Win_Makefile
Command> nmake -f Win_Makefile install

nmake -f Win_Makefile формирует версию драйвера и помещает двоичные файлы в подкаталог release. Команда nmake -f Win_Makefile install инсталлирует (вообще-то просто копирует) библиотеку драйвера и его DLL (myodbc3.lib и myodbc3.dll) в системный каталог ОС. Аналогично Вы можете сформировать версию для отладки, используя Win_Makefile_Debug:

Command> nmake -f Win_Makefile_debug
Command> nmake -f Win_Makefile_debug install

Вы можете oчищать и восстанавливать драйвер, используя команды:

Command> nmake -f Win_Makefile clean
Command> nmake -f Win_Makefile install

ОБРАТИТЕ ВНИМАНИЕ: Удостоверитесь, что определили правильные библиотеки пользователей MySQL и путь файлов заголовка в Makefile. Это принимает заданный по умолчанию путь C:\mysql\include и C:\mysql\lib\opt (для обычных DLL) или C:\mysql\lib\debug для отладочной версии.

Тестирование библиотек драйвера: после того, как библиотеки драйвера скопированы в системный каталог, Вы можете проверить качество их построения используя выборки, обеспеченные в подкаталоге samples каталога исходного текста:

Command> cd samples
Command> nmake -f Win_Makefile all

2.7.2.3 Построение MyODBC 2.50

MyODBC распространяется в исходниках как VC Project для Windows. Можно формировать драйвер, используя прямые файлы проекта VC (.dsp и .dsw), имеющиеся в дистрибутиве.

2.7.3 Установка из исходных текстов под Unix

Чтобы формировать драйвер самостоятельно под Linux, Вы должны иметь:

2.7.3.1 Требования

Как только Вы поимеете все требуемые файлы и распакуете исходные файлы в отдельный каталог, начинайте сборку драйвера как показано ниже.

2.7.3.2 Настройка

Единственные требуемые параметры; --with-mysql-libs=DIR и --with-mysql-includes=DIR. Здесь DIR задает каталог, где искать библиотеки и включаемые файлы mysql.

При использовании iodbc, если iodbc не установлен в заданное по умолчанию расположение (/usr/local), Вам придется использовать --with-iodbc=DIR или, если заголовки iODBC не находятся в DIR/include, придется использовать опцию --with-iodbc-includes=INCDIR. То же самое касается и библиотек: если они не в DIR/lib, примените явное указание параметром --with-iodbc-libs=LIBDIR.

При использовании unixODBC для создания configure ищите unixODBC вместо iODBC и используйте параметр --with-unixODBC=DIR. Здесь DIR задает то место, где установлен unixODBC.

Если звголовки и библиотеки unixODBC расположены не там, где надо (а надо в DIR/include и DIR/lib соответственно), укажите на них параметрами --with-unixODBC-libs=LIBDIR и --with-unixODBC-includes=INCDIR.

Вы можете определять другой префикс вместо /usr/local для установки, например, хранить MyODBC-драйверы в /usr/local/odbc/lib, для этого надо указать параметр --prefix=/usr/local/odbc.

Окончательно пример настройки выглядит так:

$ ./configure --prefix=/usr/local --with-iodbc=/usr/local \
              --with-mysql-libs=/usr/local/mysql/lib/mysql \
              --with-mysql-includes=/usr/local/mysql/include/mysql

2.7.3.3 Построение библиотек драйвера

Для построения библиотек драйвера Вы должны только выполнить:

$ make

Это должно сформировать библиотеки. Если происходят какие-то ошибки, исправьте их и продолжите построение. Если Вы не можете собрать пакет, пошлите детальный отчет по e-mail на myodbc@lists.mysql.com.

2.7.3.4 Установка библиотек драйвера

$ make install

Устанавливает следующий набор библиотек:

Обратите внимание, если Вы пробуете использовать make из SUN, Вы закончите с ошибками. С другой стороны, Make от GNU должен работать прекрасно на всех платформах.

2.7.3.5 Замечания для Mac OS X

Если Вы хотите формировать драйвер на Mac OS (Darwin), то используйте следующий пример выбора конфигурации:

$ ./configure --prefix=/usr/local --with-unixodbc=/usr/local \
              --with-mysql-libs=/usr/local/mysql/lib/mysql \
              --with-mysql-includes=/usr/local/mysql/include/mysql \
              --disable-shared --enable-gui=no --host=powerpc-apple

Это предполагает, что unixodbc и mysql установлены в заданные по умолчанию расположения. Если это не так, сконфигурируйте все соответственно.

2.7.3.6 Создание файлов .so

На большинстве платформ MySQL не формирует или поддерживает .so файлы, так как формирование с общедоступными библиотеками вызывало проблемы в прошлом.

В таких случаях пользователь должен скачать дистрибутив MySQL и скомпилировать его с помощью:

--without-server --enable-shared

Если Вы все же хотите формировать общедоступные библиотеки драйвера, Вы должны определить опцию настройки --enable-shared .

Если Вы конфигурировали пакет с опцией --disable-shared , то Вы можете формировать .so-файл, используя следующее:

$ cd MyODBC-3.51.01
$ make
$ cc -bundle -undefined error -o .libs/libmyodbc3-3.51.01.so *.o \
     -lz -lc -lmysqlclient -L/usr/local/mysql/lib/mysql/ \
     -compatibility_version 2 -current_version 2.0
  Это формирует и помещает файл libmyodbc3-3.51.01.so в каталог .libs
  Скопируйте этот файл в каталог библиотек MyODBC (/usr/local/lib или что
  Вы там определили в --prefix).
$ cd .libs
$ cp libmyodbc3-3.51.01.so /usr/local/lib
$ cd /usr/local/lib
$ ln -s libmyodbc3-3.51.01.so libmyodbc3.so

2.7.4 Установка из дерева исходных текстов для разработки

Предостережение: Вы должны читать этот раздел только, если Вы заинтересованы в разработке пакета. Если Вы только хотите получить MyODBC 3.51, Вы должны использовать стандартный дистрибутив (исходный текст или двоичные модули).

Чтобы получить самое современное дерево исходных текстов для разработчиков, сделайте следующее:

2.8 Поддерживаемые платформы

Драйвер MySQL ODBC может использоваться на всех основных платформах, поддерживаемых MySQL:

Вообще, MyODBC (3.51) поддержан на всех платформах, которые MySQL поддерживает. Если двоичный дистрибутив не доступен для специфической платформы, то Вы можете формировать драйвер самостоятельно, скачав его исходники. А чтобы это стало простым для других пользователей, пошлите готовые двоичные модули на myodbc@lists.mysql.com.

2.9 Список рассылки MyODBC

MySQL обеспечивает семейство пользователей своих пакетов списком рассылки, где новички получают решения от опытных пользователей, посылая запросы на myodbc@lists.mysql.com.

Чтобы подписаться на список рассылки MyODBC, пошлите сообщение на myodbc-subscribe@lists.mysql.com. Чтобы отписаться от списка рассылки MyODBC, пошлите сообщение на myodbc-unsubscribe@lists.mysql.com. Вы можете также просматривать архив списка рассылки на http://lists.mysql.com .

2.10 Поддержка MyODBC

Есть возможность получить поддержку пакета. Если Вы хотите, чтобы:

Вы должны получить контракт поддержки от MySQL AB. Фирма MySQL AB поддерживает различные типы лицензий поддержки, чтобы помочь Вам выбрать именно то, что нужно. Для получения большего количества информации относительно поддержки MySQL, посетите сайт https://order.mysql.com или пошлите e-mail на licensing@mysql.com.

Как только Вы купите поддержку, Вы сможете посылать запросы или отчеты об ошибках, используя MySQL support wizard на http://support.mysql.com, затем группа разработки MySQL начнет работать над Вашей проблемой немедленно.

2.11 Как сообщать об ошибках и проблемах с MyODBC

Если Вы сталкиваетесь с трудностями с MyODBC или с MyODBC 3.51, Вы должны запустить создание файла протокола из ODBC Manager (протокол Вы получаете при запросе файлов регистрации из ODBC ADMIN) или протокол MyODBC (или MyODBC 3.51).

Для получения трассировки ODBC через Driver Manager, Вы должны сделать следующее:

2.12 Программы, точно работающие с драйвером MyODBC

Большинство программ должно работать с MyODBC, но для каждой из перечисленных ниже это было проверено непосредственно.

Программа
Комментарий
Access
Чтобы работать с Access:
  • Если Вы используете Access 2000, Вы должны получить и установить самый новый (версия 2.6 или выше) пакет Microsoft MDAC (Microsoft Data Access Components) с http://www.microsoft.com/data. Это устранит следующую ошибку в Access: когда Вы экспортируете данные в MySQL, имена таблицы и столбца не определены. Другой путь обхода этой ошибки состоит в том, чтобы поставить MyODBC не ниже 2.50.33 и MySQL не ниже 3.23, которые вместе обеспечивают обход этой ошибки. Вы должны также получить и применить Microsoft Jet 4.0 Service Pack 5 (SP5), который может быть найден на http://support.microsoft.com/default.aspx?scid=kb;EN-US;q239114. Это исправит ряд ситуаций, в которых столбцы помечаются как удаленные (#deleted#) в Access. Обратите внимание, что, если Вы используете MySQL 3.22, Вы должны применить патч для MDAC и использовать MyODBC 2.50.32 или 2.50.34 и выше для решения проблемы.
  • Для всех версий Access Вы должны включить опцию MyODBC Return matching rows. Для Access 2.0 Вы должны дополнительно включить опцию Simulate ODBC 1.0.
  • Вы должны иметь timestamp во всех таблицах, которые Вы хотите модифицировать. Для максимальной мобильности TIMESTAMP(14) или просто TIMESTAMP рекомендуются вместо других вариантов TIMESTAMP(X).
  • Вы должны иметь первичный ключ в таблице. Если это не так, новые или модифицируемые строки могут обнаруживаться как #DELETED#.
  • Используйте только поля DOUBLE с плавающей точкой. Access рушится при сравнении с single-полями с плавающей точкой. Это приводит к тому, что новые или модифицируемые строки могут обнаруживаться как #DELETED#, или Вы не можете находить или модифицировать строки.
  • Если Вы связываете таблицу, которая имеет BIGINT как один из столбца, через MyODBC, то результаты будут отображаться как #DELETED. Обойти это можно так:
    • Создайте еще один фиктивный столбец с TIMESTAMP как тип данных, предпочтительно TIMESTAMP(14).
    • Проверьте Change BIGINT columns to INT в диалоге опций соединения в ODBC DSN Administrator.
    • Удалите связь таблицы из и пересоздайте ее.
    Это все еще отображает предыдущие записи как #DELETED#, но новые записи будут отображаться правильно.
  • Если Вы все еще получаете ошибку Another user has changed your data после добавления столбца TIMESTAMP, следующий прием может помочь: не используйте представление листа данных таблицы. Создайте взамен форму с полями, которые Вы хотите видеть, и используйте вид form листа данных. Вы должны установить реквизит DefaultValue для столбца TIMESTAMP в NOW(). Стоит сделать столбец TIMESTAMP скрытым.
  • В некоторых случаях Access может генерировать запрещенные запросы SQL, которые MySQL не может понимать. Вы можете исправить это, выбирая Query|SQLSpecific|Pass-Through из меню Access.
  • Access под NT показывает столбцы BLOB как OLE OBJECTS. Если Вы хотите иметь столбцы MEMO вместо этого, Вы должны изменить тип столбца на TEXT с помощью команды ALTER TABLE.
  • Access не может всегда обрабатывать столбцы DATE правильно. Если Вы имеете проблему с ними, измените столбцы на DATETIME: с ними путаницы нет.
  • Если Вы имеете в Access столбец, определенный как BYTE, Access пробует экспортировать это как TINYINT вместо TINYINT UNSIGNED. Это задаст Вам проблем, если Вы имеете значения > 127 в этом столбце!
ADO
Когда Вы программируете с ADO API и MyODBC Вы должны обратить внимание на некоторые заданные по умолчанию свойства, которые пока не поддержаны сервером MySQL. Например, использование свойства CursorLocation Property как adUseServer возвратит для реквизита RecordCount Property -1. Чтобы иметь правильное значение, Вы должны установить это свойство в adUseClient, как показано в этом коде на VB:
Dim myconn As New ADODB.Connection
Dim myrs As New Recordset
Dim mySQL As String
Dim myrows As Long

myconn.Open "DSN=MyODBCsample"
mySQL = "SELECT * from user"
myrs.Source = mySQL
Set myrs.ActiveConnection = myconn
myrs.CursorLocation = adUseClient
myrs.Open
myrows = myrs.RecordCount

myrs.Close
myconn.Close
Другой обход: использовать инструкцию SELECT COUNT(*) для подобного запроса, чтобы получить правильное число строк.
Active server pages (ASP)
Вы должны использовать параметр Return matching rows.
Приложения BDE
Вы должны установить параметры Don't optimize column widths и Return matching rows. Тогда все должно работать.
Borland Builder 4
Когда Вы запускаете запрос, Вы можете использовать свойство Active или метод Open. Обратите внимание, что Active запускается автоматически при выдаче запроса SELECT * FROM ..., что медленно, если Ваши таблицы большие.
ColdFusion (под Unix)
Следующая информация найдена в документации на ColdFusion: используйте следующую информацию, чтобы конфигурировать ColdFusion Server для Linux, чтобы использовать драйвер unixODBC с MyODBC для источников данных MySQL. Известно, что MyODBC Version 2.50.26 работает с MySQL Version 3.22.27 и с ColdFusion для Linux. Любая более новая версия должна также работать. Вы можете скачать MyODBC с http://www.mysql.com/downloads/api-myodbc.html. ColdFusion Version 4.5.1 позволяет использовать ColdFusion Administrator, чтобы добавлять источник данных MySQL. Однако, драйвер не включен в поставку ColdFusion Version 4.5.1. Прежде, чем драйвер MySQL появится в раскрывающемся списке ODBC datasources, Вы должны сформировать и скопировать драйвер MyODBC в /opt/coldfusion/lib/libmyodbc.so. Каталог Contrib хранит программу mydsn-xxx.zip, которая позволяет Вам формировать и удалять DSN-файл системного реестра для драйвера MyODBC в программах Coldfusion.
DataJunction
Вы должны обновить пакет, иначе будет выводиться ENUM вместо VARCHAR: проблемы с протоколом.
Excel
Работает нормально. Некоторые советы:
  • Если Вы имеете проблемы с датами, попробуйте выбирать их как строки, использующие функцию CONCAT(). Например:
    select CONCAT(rise_time), CONCAT(set_time) from sunrise_sunset;
    
    Значения, полученные как строки этим способом, должны быть правильно распознаны как значения времени Excel97. Цель CONCAT() в этом примере состоит в том, чтобы ввести в заблуждение ODBC в плане того, что столбец имеет строковый тип. Без CONCAT() ODBC знает, что столбец имеет тип time, а Excel не понимает этого. Обратите внимание, что это ошибка в Excel, поскольку он автоматически преобразовывает строку в time, хотя никто его об этом не просит. Это было бы большим удобством, если источником является текстовый файл, но просто глупо, когда в качестве источника данных выступает ODBC-подключение, которое сообщает точные типы для каждого столбца.
Word
Чтобы получать данные из MySQL в документах Word/Excel, надо использовать драйвер MyODBC и Add-in Microsoft Query help. Например, создайте базу данных с таблицей, содержащей 2 столбца текста:
  • Вставьте строки, используя инструмент командной строки mysql.
  • Создайте DSN-файл, использующий MyODBC-драйвер, например, my.
  • Откройте Word.
  • Создайте пустой новой документ.
  • При использовании панели инструментов Database, нажмите кнопку insert database.
  • Нажмите кнопку Get Data.
  • С правой стороны окна Get Data нажмите кнопку Ms Query.
  • В Ms Query создайте New Data Source, используя DSN-файл my.
  • Выберите новый запрос.
  • Выберите столбцы, которые Вы хотите.
  • Создайте фильтр, если он нужен.
  • Выполните сортировку, если она нужна.
  • Установите Return Data в Microsoft Word.
  • Нажмите кнопку Finish.
  • Нажмите Insert data и выберите записи.
  • Теперь после нажатия на OK строки появятся в Вашем документе Word.
Delphi
Вы должны использовать BDE Version 3.2 или более новую. Установите опцию Don't optimize column width при соединении с MySQL. Также имеется некоторый потенциально полезный Delphi-код, который устанавливает ODBC-вход и BDE-вход для MyODBC (BDE-вход требует BDE Alias Editor, который можно свободно скачать с Delphi Super Page.
fReg:= TRegistry.Create;
  fReg.OpenKey('\Software\ODBC\ODBC.INI\DocumentsFab', True);
  fReg.WriteString('Database', 'Documents');
  fReg.WriteString('Description', ' ');
  fReg.WriteString('Driver', 'C:\WINNT\System32\myodbc.dll');
  fReg.WriteString('Flag', '1');
  fReg.WriteString('Password', '');
  fReg.WriteString('Port', ' ');
  fReg.WriteString('Server', 'xmark');
  fReg.WriteString('User', 'winuser');
  fReg.OpenKey('\Software\ODBC\ODBC.INI\ODBC Data Sources', True);
  fReg.WriteString('DocumentsFab', 'MySQL');
  fReg.CloseKey;
  fReg.Free;

  Memo1.Lines.Add('DATABASE NAME=');
  Memo1.Lines.Add('USER NAME=');
  Memo1.Lines.Add('ODBC DSN=DocumentsFab');
  Memo1.Lines.Add('OPEN MODE=READ/WRITE');
  Memo1.Lines.Add('BATCH COUNT=200');
  Memo1.Lines.Add('LANGDRIVER=');
  Memo1.Lines.Add('MAX ROWS=-1');
  Memo1.Lines.Add('SCHEMA CACHE DIR=');
  Memo1.Lines.Add('SCHEMA CACHE SIZE=8');
  Memo1.Lines.Add('SCHEMA CACHE TIME=-1');
  Memo1.Lines.Add('SQLPASSTHRU MODE=SHARED AUTOCOMMIT');
  Memo1.Lines.Add('SQLQRYMODE=');
  Memo1.Lines.Add('ENABLE SCHEMA CACHE=FALSE');
  Memo1.Lines.Add('ENABLE BCD=FALSE');
  Memo1.Lines.Add('ROWSET SIZE=20');
  Memo1.Lines.Add('BLOBS TO CACHE=64');
  Memo1.Lines.Add('BLOB SIZE=32');

  AliasEditor.Add('DocumentsFab','MySQL',Memo1.Lines);
C++ Builder
Тестировался с BDE Version 3.0. Единственная известная проблема состоит в том, что, когда схема таблицы изменилась, поля запроса не модифицируются. BDE, кажется, не распознает первичные ключи, только PRIMARY индекс, хотя это не было проблемой.
Vision
Вы должны использовать параметр Return matching rows.
Visual Basic
Чтобы модифицировать таблицу, Вы должны определить первичный ключ для таблицы. Visual Basic с ADO не может обрабатывать большие целые числа. Это означает, что некоторые запросы подобно SHOW PROCESSLIST не будут работать правильно. Установите опцию OPTION=16834 в строке подключения ODBC или задайте параметр Change BIGINT columns to INT на экране соединения MyODBC. Вы можете также устанавливать опцию Return matching rows.
VisualInterDev
Если Вы получаете ошибку [Microsoft][ODBC Driver Manager] Driver does not support this parameter, причина может быть в том, что Вы имеете BIGINT в Вашем результате. Попробуйте установить параметр Change BIGINT columns to INT на экране соединения MyODBC.
Visual Objects
Вы должны использовать параметр Don't optimize column widths.
MS Visio Enterprise 2000
Пользователи сделали диаграмму модели базы данных, подключаясь из MS Vision Enterprise 2000 к MySQL через MyODBC (2.50.37 или более новый) и используя функцию обратной разработки в Visio, чтобы восстановить информацию относительно базы данных (Visio показывает все определения столбца, первичные ключи, индексы и так далее). Также разрабатывали новые таблицы в Visio и экспортировали их в MySQL через MyODBC. Все работало.

3 Разработка прикладных программы, используя MyODBC

Эта глава содержит информацию относительно разработки прикладных программ, которые используют MyODBC как интерфейс, чтобы обратиться к серверу MySQL.

3.1 Базисные шаги прикладной программы MyODBC

В общем виде, чтобы работать с сервером MySQL из любой программы через ODBC/MyODBC, надо сделать следующее:

Большинство прикладных программ использует некоторое изменение этих шагов.

3.2 Настройка MyODBC DSN

Источник данных идентифицирует путь для данных, который может включать сетевую библиотеку, сервер, базу данных и другие атрибуты. В нашем случае источник данных представляет собой путь к базе данных MySQL. Чтобы соединиться с источником данных, Driver Manager проверяет системный реестр Windows для получения специфической информации подключения.

ODBC Driver Manager и MyODBC Drivers использует вход системного реестра, созданный ODBC Data Source Administrator . Этот вход содержит информацию относительно каждого источника данных и связанного с ним драйвера. Прежде, чем Вы сможете соединяться с источником данных, информация о подключении должна быть добавлена к системному реестру.

Чтобы добавлять и конфигурировать источники данных, используйте ODBC Data Source Administrator. ODBC Administrator модифицирует информацию о подключениях к источникам данных. Поскольку Вы добавляете источники данных, ODBC Administrator модифицирует информацию системного реестра для них.

Чтобы открыть ODBC Administrator из Control Panel:

Чтобы добавить источник данных в Windows:

  1. Откройте ODBC Data Source Administrator.
  2. В диалоговом окне ODBC Data Source Administrator нажмите Add. Откроется диалоговое окно Create New Data Source.
  3. Выберите там MySQL ODBC 3.51 Driver и нажмите на Finish. Появится диалоговое окно MySQL ODBC 3.51 Driver - DSN Configuration.
  4. В окне Data Source Name впечатайте имя источника данных, к которому Вы хотите обращаться. Это может быть любое имеющее силу имя, которое понравилось.
  5. В окне Description введите описание необходимое для DSN.
  6. В окне Host or Server Name (or IP) напечатайте имя сервера MySQL, к которому Вы хотите обращаться. По умолчанию это local host.
  7. В окне Database Name укажите имя MySQL базы данных, которая будет применяться как заданная по умолчанию база данных.
  8. В окне User задайте имя пользователя базы данных (user ID).
  9. В окне Password надо задать пароль.
  10. В окне Port напечатайте номер порта, если это не значение по умолчанию 3306.
  11. В окне SQL Command Вы можете вводить факультативную команду SQL, которую серверу надлежит выполнить сразу после установления подключения.

Теперь нажмите OK, чтобы добавить этот источник данных. Обратите внимание: при щелчке на OK диалоговое окно Data Sources dialog, и ODBC Administrator модифицирует информацию системного реестра. Имя пользователя и строка подключения станут заданными по умолчанию значениями подключения для этого источника данных. Вы можете также проверить, достаточны ли Ваши параметры настройки, чтобы соединиться с сервером, используя кнопку Test Data Source. Эта возможность появилась только начиная с MyODBC 3.51.

Driver Options: Вы можете также видеть кнопку Options, которая отобразит диалог дополнительных параметров, которые управляют поведением драйвера.

Обратите внимание, что параметры Driver Trace Options будут заблокированы (нарисованы серым цветом) при использовании обычной версии DLL.

Чтобы изменить источник данных в Windows:

  1. Откройте окно ODBC Data Source Administrator . Выберите соответствующую вкладку DSN.
  2. Выберите источник данных MySQL, который Вы хотите изменить, а затем нажмите modify и щелкните по Configure. Откроется диалоговое окно MySQL ODBC 3.51 Driver - DSN Configuration.
  3. Измените соответствующие поля источника данных, а затем нажмите OK.

Когда Вы закончите изменять информацию в этом диалоговом окне, ODBC Administrator модифицирует информацию системного реестра.

Чтобы настроить источник данных в Unix:

В Unix Вы можете конфигурировать DSN-входы непосредственно в файле ODBC.INI. Имеется пример файла odbc.ini с myodbc как DSN-имя для MyODBC 2.50 и myodbc3 для MyODBC 3.51 Drivers:

  ;
  ;  odbc.ini configuration for MyODBC and MyODBC 3.51 Drivers
  ;
  [ODBC Data Sources]
  myodbc  = MySQL ODBC 2.50 Driver DSN
  myodbc3 = MySQL ODBC 3.51 Driver DSNа

  [myodbc]
  Driver      = /usr/local/lib/libmyodbc.so
  Description = MySQL ODBC 2.50 Driver DSN
  SERVER      = localhost
  PORT        =
  USER        = root
  Password    =
  Database    = test
  OPTION      = 3
  SOCKET      =

  [myodbc3]
  Driver      = /usr/local/lib/libmyodbc3.so
  Description = MySQL ODBC 3.51 Driver DSN
  SERVER      = localhost
  PORT        =
  USER        = root
  Password    =
  Database    = test
  OPTION      = 3
  SOCKET      =

  [Default]
  Driver      = /usr/local/lib/libmyodbc3.so
  Description = MySQL ODBC 3.51 Driver DSN
  SERVER      = localhost
  PORT        =
  USER        = root
  Password    =
  Database    = test
  OPTION      = 3
  SOCKET      =

Обратите внимание: если Вы используете unixODBC, то Вы можете использовать следующие инструментальные средства чтобы настроить DSN:

3.3 Параметры подключения

Можно определять следующие параметры для MyODBC или для MyODBC 3.51 в секции [Data Source Name] файла ODBC.INI или через параметр InConnectionString в вызове SQLDriverConnect().

ПараметрЗначение по умолчанию Комментарий
userODBC (в Windows)Имя пользователя для связи с MySQL.
serverlocalhostИмя сервера MySQL.
databaseБаза данных по умолчанию
option0Целое число, которым Вы можете определять как должен работать MyODBC 3.51. Описано чуть ниже.
port3306Порт TCP/IP, чтобы использовать, если server не равен localhost.
stmtИнструкция, которая будет выполнена, когда установлено подключение к MySQL.
passwordПароль для комбинации server user.
socketСокет или именованный канал Windows для связи.

Параметр OPTION используется, чтобы сообщить MyODBC 3.51, что пользователь не на 100% совместим с ODBC. Следующие параметры перечислены в том же самом порядке, в каком они появляются в MyODBC 3.51:

БитОписание
1Пользователь не может обрабатывать ситуацию, когда MyODBC возвращает реальную ширину столбца.
2Пользователь не может обрабатывать ситуацию, когда MySQL возвращает истинное число обработанных строк. Если этот параметр установлен, MySQL вернет число найденных строк. Нужно иметь MySQL 3.21.14 или более новый, чтобы это работало.
4Создать протокол трассировки в файле c:\myodbc.log (/tmp/myodbc.log). Это аналогично указанию MYSQL_DEBUG=d:t:O,c::\myodbc.log в AUTOEXEC.BAT.
8Не устанавливать ограничений пакета для результатов и параметров.
16-Не запрашивать ничего, даже если драйвер хочет запросить.
32Включить или отключить поддержку динамического курсора. Это не работает в MyODBC 2.50.
64Игнорировать использование имени базы данных в формате database.table.column.
128Использование экспериментальных курсоров ODBC manager.
256Отключить использование расширенной (экспериментальной) выборки.
512Дополнить поля типа CHAR до полной длины столбца.
1024SQLDescribeCol() возвратит полностью квалифицированные имена столбцов.
2048Использовать сжатый протокол клиент-сервер.
4096Сервер должен игнорировать пробел между именем функции и '(' (нужно для Power Builder). Это делает все ключевые слова именами функций!
8192Соединиться через именованный канал с сервером mysqld под NT.
16384Менять столбцы типа LONGLONG на столбцы INT (некоторые прикладные программы не могут корректно обрабатывать LONGLONG).
32768Вернуть user как Table_qualifier и Table_owner из SQLTables.
65536Читать параметры из групп client и odbc в файле my.cnf
131072Добавить некоторые дополнительные проверки безопасности (вроде бы не очень и надо, но...).
262144Выключить использование транзакций
524288Включить регистрацию запросов в файле c:\myodbc.sql (/tmp/myodbc.sql). Доступно только в режиме отладки в специальной версии драйвера.

Если Вы хотите иметь много параметров, Вы должны сложить вышеупомянутые числа. Например, установка опции в 12 (4+8) дает Вам отладку без ограничений на размеры пакета.

По умолчанию MYODBC3.DLL компилируется для оптимальной эффективности. Если Вы хотите отладить MyODBC 3.51 (например, чтобы получить трассировку), используйте MYODBCD3.DLL вместо стандартного файла MYODBC3.DLL.

3.4 Связь с сервером MySQL

Прикладная программа может быть связана с любом числом источников данных и драйверов. Они могут быть вариантами того же самого драйвера и ряда источников данных или несколькими подключениями с тем же самым драйвером и источником данных. Прикладная программа должна сделать следующее, чтобы соединиться с сервером MySQL через MyODBC:

3.4.1 Распределение дескриптора среды

Прежде, чем прикладная программа сможет использовать любую функцию ODBC, надо инициализировать ODBC-связь с помощью интерфейса и сопоставить с ней дескриптор среды. Он обеспечивает доступ к глобальной информации типа имеющих силу дескрипторов подключения и активных дескрипторов подключения.

Чтобы распределить правильный дескриптор среды, прикладная программа:

  1. Объявляет переменную типа SQLHENV. Например, прикладная программа могла бы использовать объявление:
    SQLHENV henv;
    
  2. Вызывает SQLAllocHandle (в MyODBC 2.50 называется SQLAllocEnv) и передает адрес этой переменной и опции SQL_HANDLE_ENV как:
    SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv) или
    SQLAllocEnv(&henv)
    

Если прикладная программа связана через Driver Manager, то это обращение загружает Driver Manager. Он не вызывает SQLAllocHandle в драйвере потому, что пока не знает, который драйвер вызвать. Это откладывает вызов SQLAllocHandle в драйвере до получения вызовов из прикладной программы, чтобы соединиться с источником данных: тогда-то будет однозначно ясно, какой драйвер нужен.

Если прикладная программа связана непосредственно с драйвером, то это обращение загружает драйвер, и уже драйвер формирует информацию среды и возвращает распределенную структуру обратно прикладной программе.

3.4.2 Установка версии ODBC

Если Вы используете драйвер MyODBC 2.50, то Вы можете игнорировать этот раздел. Прежде, чем прикладная программа создаст соединение, необходимо установить атрибут SQL_ATTR_ODBC_VERSION среды, используя SQLSetEnvAttr:

SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, 0);

Этот атрибут заявляет, что прикладная программа следует спецификациям ODBC 2.x или ODBC 3.x при использовании следующих элементов:

MyODBC 3.51 контролирует версию спецификации ODBC, для которой прикладная программа написана и отвечает соответственно. Например, если прикладная программа следует версии ODBC 2.x и вызывает SQLExecute до вызова SQLPrepare, драйвер вернет: SQLSTATE S1010 (Function sequence error). Если прикладная программа поддерживает спецификацию ODBC 3.x, то это возвращает: SQLSTATE HY010 (Function sequence error).

3.4.3 Распределение дескриптора подключения

Дескриптор подключения обеспечивает доступ к информации относительно того, является ли подключение открытым или нет, имеют ли силу операторные и дескрипторные маркеры на подключении, и открыта ли сейчас транзакция.

Прежде, чем прикладная программа сможет соединиться с сервером MySQL или с драйвером, она должна распределить дескриптор подключения, следующим образом:

Если прикладная программа связана через Driver Manager, то Driver Manager распределяет память, чтобы сохранить информацию относительно подключения и возвращает дескриптор подключения прикладной программе. С другой стороны, если Вы непосредственно компонуете программу через библиотеку драйверов вместо Driver Manager, то эту работу делает уже драйвер.

3.4.4 Установка атрибутов соединения (подключения)

Атрибуты подключения представляют собой характеристики подключения. Например, они определяют, что транзакции происходят в уровне подключения, а уровень изоляции транзакции представляет собой атрибут подключения. Точно так же время ожидания входа в систему или число секунд, которые надо ждать при попытке соединиться перед тайм-аутом, тоже атрибуты подключения.

Атрибуты подключения установлены с помощью SQLSetConnectAttr, а их текущие параметры настройки могут быть получены с помощью SQLGetConnectAttr. Для прикладных программ драйвера MyODBC 2.50 Вы можете использовать SQLSetConnectOption и SQLGetConnectOption.

Атрибуты подключения могут быть установлены до или после подключения, в зависимости от типа атрибута. Время ожидания входа в систему SQL_ATTR_LOGIN_TIMEOUT применяется только при установлении связи и важно, только если установлено перед соединением.

Атрибуты, которые определяют, использовать ли библиотеку курсоров ODBC (SQL_ATTR_ODBC_CURSORS) и сетевой размер пакета (SQL_ATTR_PACKET_SIZE), должны быть установлены прежде, чем соединение создано потому что, библиотека курсоров ODBC находится между Driver Manager и драйвером, а следовательно должно быть загружена перед драйвером. Подробный перечень атрибутов подключения, поддерживаемых драйверами MyODBC, есть в разделе "4.5.1 SQLSetConnectAttr".

3.4.5 Установление подключения, использующего MyODBC

После распределения среды и дескрипторов подключения и установки факультативных атрибутов подключения, прикладная программа готова соединиться с сервером MySQL или драйвером MyODBC (через Driver Manager). Имеются две различных функции для этого:

3.4.5.1 Соединение через SQLConnect

SQLConnect самая простая функция подключения. Требует имя источника данных и принимает факультативные user ID и пароль. Прикладная программа передает следующую информацию драйверу через SQLConnect:

DSN: имя источника данных.
UID: имя пользователя для связи с сервером (опционально).
PWD: соответствующий пароль (опционально).

Обратите внимание, что, если Вы уже определили имя пользователя и пароль в параметрах DSN или непосредственно в файле ODBC.INI, Вы можете только определить имеющий силу DSN, а драйвер внутренне получает другую требуемую информацию из записей в DSN сам.

Когда из прикладной программы вызван SQLConnect, Driver Manager использует имя источника данных, чтобы прочитать имя драйвера DLL из соответствующего раздела файла ODBC.INI или из системного реестра. Это затем загружает драйвер DLL и передает ему параметры SQLConnect. Если драйвер нуждается в дополнительной информации, чтобы соединиться с источником данных, он читает эту информацию из того же самого раздела файла ODBC.INI.

Если прикладная программа определяет имя источника данных, которое не значится в файле ODBC.INI или в системном реестре, или если прикладная программа не определяет имя источника данных, Driver Manager ищет заданную по умолчанию спецификацию источника данных. Если он находит заданный по умолчанию источник данных, то загружает заданный по умолчанию драйвер и передает ему определенное прикладная программой имя источника данных. Если не имеется никакого заданного по умолчанию источника данных, Driver Manager возвращает соответствующую ошибку.

Пример: следующий пример распределяет необходимую среду, дескриптор подключения и соединяется с сервером MySQL, используя DSN myodbc3.

SQLHENV    henv;
SQLHDBC    hdbc;
SQLHSTMT   hstmt;
SQLRETURN  retcode;

/* Allocate environment handle */
retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
{
   /* Set the ODBC version environment attribute to version 3 */
   retcode = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION,
                           (SQLPOINTER)SQL_OV_ODBC3, 0);
   if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
   {
      /* Allocate connection handle */
      retcode = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
      if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
      {
         /* Connect to data source myodbc3 */
         retcode = SQLConnect(hdbc, (SQLCHAR*) "myodbc3", SQL_NTS,
                              (SQLCHAR*) "myuser", SQL_NTS,
                              (SQLCHAR*) "mypassword", SQL_NTS);
         if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
         {
            /* Set auto commit to ON */
            retcode = SQLSetConnectAttr(hdbc, SQL_ATTR_AUTO_COMMIT,
                                        SQL_AUTOCOMMIT_ON,0);
            printf("\n autocommit returned :%d", redcode);
            /* Allocate statement handle */
            retcode = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
            if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
            {
               /* Process data */
                  ;
                  ;
                  ;
               /* Free stattemt handle */
               SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
            }
            /* Disconnect from the server */
            SQLDisconnect(hdbc);
         }
         /* Close the connection handle */
         SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
      }
   }
   /* Close the environment handle */
   SQLFreeHandle(SQL_HANDLE_ENV, henv);

3.4.5.2 Связь через SQLDriverConnect

SQLDriverConnect используется, чтобы соединиться с сервером, используя строку подключения. Можно использовать SQLDriverConnect вместо SQLConnect по следующим причинам:

Строка подключения может состоять из одного или большего количества параметров MyODBC подключения, отделяемых точкой с запятой (;). Если драйвер должен запрашивать пользователя относительно информации подключения, то он отображает диалог подключения.

3.4.5.3 Строка подключения для SQLDriverConnect

Используя myodbc3 как MySQL ODBC 3.51 DSN:

ConnectionString = "DSN=myodbc3"

DSN Less Connection:

ConnectionString = "DRIVER={MySQL ODBC 3.51 Driver}; SERVER=localhost;\
                    DATABASE=test; USER=monty; PASSWORD=monty;\
                    OPTION=4;"

3.4.6 Получение информации о драйвере и источнике данных

Как только подключение установлено, прикладная программа должна получить большее количество информации относительно драйвера и источника данных, с которым он связан. Использование следующего API поможет это устроить: