Скачивание драйвера odbc driver for sql serverdownload odbc driver for sql server

SQLConnectSQLConnect

SQLConnect — это простейшая функция подключения.SQLConnect is the simplest connection function. Она принимает три параметра: имя источника данных, идентификатор пользователя и пароль.It accepts three parameters: a data source name, a user ID, and a password. Используйте SQLConnect , если эти три параметра содержат всю информацию, необходимую для подключения к базе данных.Use SQLConnect when these three parameters contain all the information needed to connect to the database. Для этого создайте список источников данных с помощью SQLDataSources; запрашивать у пользователя источник данных, идентификатор пользователя и пароль; затем вызовите SQLConnect.To do this, build a list of data sources using SQLDataSources; prompt the user for a data source, user ID, and password; and then call SQLConnect.

SQLConnect предполагает, что имя источника данных, идентификатор пользователя и пароль достаточно для подключения к источнику данных и что источник данных ODBC содержит все остальные сведения, необходимые драйверу ODBC для подключения.SQLConnect assumes that a data source name, user ID, and password are sufficient to connect to a data source and that the ODBC data source contains all other information the ODBC driver needs to make the connection. В отличие от SQLDriverConnect и SQLBrowseConnect, SQLConnect не использует строку подключения.Unlike SQLDriverConnect and SQLBrowseConnect, SQLConnect does not use a connection string.

Connecting to a Database

Databases can be connected by specifying a connection string directly,
or with DSN configuration files.

Connection Strings

Specify a connection string as named arguments directly in the
method.

library(DBI)
con <- dbConnect(odbc::odbc(),
  driver = "PostgreSQL Driver",
  database = "test_db",
  uid = "postgres",
  pwd = "password",
  host = "localhost",
  port = 5432)
library(DBI)
con <- dbConnect(odbc::odbc(),
  .connection_string = "Driver={PostgreSQL Driver};Uid=postgres;Pwd=password;Host=localhost;Port=5432;Database=test_db;")

DSN Configuration files

ODBC configuration files are another option to specify connection
parameters and allow one to use a Data Source Name (DSN) to make it
easier to connect to a database.

con <- dbConnect(odbc::odbc(), "PostgreSQL")

MacOS / Linux

On MacOS and Linux there are two separate text files that need to be
edited. UnixODBC includes a command line executable which can
be used to query and modify the DSN files. However these are plain text
files you can also edit by hand if desired.

There are two different files used to setup the DSN information.

  • — which defines driver options
  • — which defines connection options

The DSN configuration files can be defined globally for all users of the
system, often at or , the exact
location depends on what option was used when compiling unixODBC.
can be used to find the exact location. Alternatively the
environment variable can be used to specify the location of
the configuration files. Ex.

A local DSN file can also be used with the files and
.

odbcinst.ini

Contains driver information, particularly the name of the driver
library. Multiple drivers can be specified in the same file.

Driver          = /usr/local/lib/psqlodbcw.so


Driver          = /usr/local/lib/libsqlite3odbc.dylib
odbc.ini

Contains connection information, particularly the username, password,
database and host information. The Driver line corresponds to the driver
defined in .

Driver              = PostgreSQL Driver
Database            = test_db
Servername          = localhost
UserName            = postgres
Password            = password
Port                = 5432


Driver          = SQLite Driver
Database=/tmp/testing

Компоненты Microsoft ODBC Driver for SQL ServerSQL Server в WindowsComponents of the Microsoft ODBC Driver for SQL ServerSQL Server on Windows

Драйвер ODBC для Windows состоит из следующих компонентов:The ODBC driver on Windows contains the following components:

КомпонентComponent ОписаниеDescription
msodbcsql17.dll илиmsodbcsql17.dll or msodbcsql13.dll илиmsodbcsql13.dll or msodbcsql11.dllmsodbcsql11.dll Файл библиотеки динамической компоновки (DLL), содержащий все функциональные возможности драйвера.The dynamic-link library (DLL) file that contains all of the driver’s functionality. Этот файл устанавливается в папку %SYSTEMROOT%\System32.This file is installed in %SYSTEMROOT%\System32.
msodbcdiag17.dll илиmsodbcdiag17.dll or msodbcdiag13.dll илиmsodbcdiag13.dll or msodbcdiag11.dllmsodbcdiag11.dll Файл библиотеки динамической компоновки (DLL), содержащий интерфейс диагностики (трассировка).The dynamic-link library (DLL) file that contains the driver’s diagnostics (tracing) interface. Этот файл устанавливается в папку %SYSTEMROOT%\System32.This file is installed in %SYSTEMROOT%\System32.
msodbcsqlr17.rll илиmsodbcsqlr17.rll or msodbcsqlr13.rll илиmsodbcsqlr13.rll or msodbcsqlr11.rllmsodbcsqlr11.rll Сопутствующий файл ресурса для библиотеки драйвера.The accompanying resource file for the driver library. Этот файл устанавливается в папку %SYSTEMROOT%\System32\1033.This file is installed in %SYSTEMROOT%\System32\1033.
s13ch_msodbcsql.chm илиs13ch_msodbcsql.chm or s11ch_msodbcsql.chms11ch_msodbcsql.chm Файл справки мастера источников данных, описывающий, как создать источник данных для драйвера.The Data Source Wizard help file that documents how to create a data source for the driver. Этот файл устанавливается в папку %SYSTEMROOT%\System32\1033This file is installed in %SYSTEMROOT%\System32\1033 ПРИМЕЧАНИЕ. Для драйвера ODBC 17 отсутствует CHM-файл.NOTE: There is no chm file for ODBC Driver 17.
msodbcsql.hmsodbcsql.h Файл заголовка, содержащий все новые определения, необходимые для использования драйвера.The header file that contains all of the new definitions needed to use the driver.Примечание. В одной программе нельзя сочетать ссылки на msodbcsql.h и odbcss.h.Note: You cannot reference msodbcsql.h and odbcss.h in the same program.Файл msodbcsql.h для ODBC Driver 17 или 13 устанавливается в папку %PROGRAMFILES%\Microsoft SQL Server\Client SDK\ODBC\130\SDK.msodbcsql.h for ODBC Driver 17 or 13 is installed in %PROGRAMFILES%\Microsoft SQL Server\Client SDK\ODBC\130\SDK. Файл msodbcsql.h для ODBC Driver 11 устанавливается в папку %PROGRAMFILES%\Microsoft SQL Server\Client SDK\ODBC\110\SDK.msodbcsql.h for ODBC Driver 11 is installed in %PROGRAMFILES%\Microsoft SQL Server\Client SDK\ODBC\110\SDK.
msodbcsql17.lib илиmsodbcsql17.lib or msodbcsql13.lib илиmsodbcsql13.lib or msodbcsql11.libmsodbcsql11.lib Файл библиотеки, необходимый для вызова функций служебной программы bcp, являющихся частью драйвера.The library file needed to call the bcp utility functions that are part of the driver.Примечание. Если вы включаете в программу ссылку на этот файл библиотеки, убедитесь, что этот файл находится в вашем системном пути, а также в системном пути других пользователей, которые используют это приложение.Note: If you do reference this library file in your program, make sure that it is in your system path and in the system path of those that use the application.Файл msodbcsql17.lib или msodbcsql13.lib устанавливается в папку %PROGRAMFILES%\Microsoft SQL Server\Client SDK\ODBC\130\SDK.msodbcsql17.lib or msodbcsql13.lib is installed in %PROGRAMFILES%\Microsoft SQL Server\Client SDK\ODBC\130\SDK.msodbcsql11.lib устанавливается в папку %PROGRAMFILES%\Microsoft SQL Server\Client SDK\ODBC\110\SDK.msodbcsql11.lib is installed in %PROGRAMFILES%\Microsoft SQL Server\Client SDK\ODBC\110\SDK.
   

SQLBrowseConnectSQLBrowseConnect

SQLBrowseConnect, например SQLDriverConnect, использует строку подключения.SQLBrowseConnect, like SQLDriverConnect, uses a connection string. Однако с помощью SQLBrowseConnectприложение может итеративно создавать полную строку соединения с источником данных во время выполнения.However, by using SQLBrowseConnect, an application can construct a complete connection string iteratively with the data source at run time. Это позволяет приложению:This allows the application to do two things:

  • строить собственные диалоговые окна для запроса этой информации, сохраняя таким образом управление своим пользовательским интерфейсом;Build its own dialog boxes to prompt for this information, thereby retaining control over its user interface.

  • просматривать систему в поисках источников данных, которые может использовать конкретный драйвер, возможно, за несколько шагов.Browse the system for data sources that can be used by a particular driver, possibly in several steps.

    Например, пользователь может сначала просмотреть серверы в сети, а после выбора сервера с помощью драйвера просмотреть доступные базы данных этого сервера.For example, the user might first browse the network for servers and, after choosing a server, browse the server for databases accessible by the driver.

Когда SQLBrowseConnect завершает успешное подключение, он возвращает строку подключения, которую можно использовать при последующих вызовах SQLDriverConnect.When SQLBrowseConnect completes a successful connection, it returns a connection string that can be used on subsequent calls to SQLDriverConnect.

SQL ServerSQL ServerДрайвер ODBC для собственного клиента всегда возвращает SQL_SUCCESS_WITH_INFO для успешных SQLConnect, SQLDriverConnectили SQLBrowseConnect.The SQL ServerSQL Server Native Client ODBC driver always returns SQL_SUCCESS_WITH_INFO on a successful SQLConnect, SQLDriverConnect, or SQLBrowseConnect. Когда приложение ODBC вызывает SQLGetDiagRec после получения SQL_SUCCESS_WITH_INFO, оно может получать следующие сообщения:When an ODBC application calls SQLGetDiagRec after getting SQL_SUCCESS_WITH_INFO, it can receive the following messages:

57015701Показывает, что SQL ServerSQL Server помещает пользовательский контекст в базу данных по умолчанию, которая определена в источнике данных, или в базу данных, определенную для идентификатора входа, который использовался в соединении, если источник данных не имеет базы данных по умолчанию.Indicates that SQL ServerSQL Server put the user’s context into the default database defined in the data source, or into the default database defined for the login ID used in the connection if the data source did not have a default database.

57035703Обозначает язык, используемый на сервере.Indicates the language being used on the server.

В следующих примерах показано сообщение, которое возвращается системным администратором при успешном соединении:The following example shows the message returned on a successful connection by the system administrator:

Можно не обрабатывать сообщения 5701 и 5703; они всего лишь информационные.You can ignore messages 5701 and 5703; they are only informational. Однако не следует пропускать код возврата SQL_SUCCESS_WITH_INFO, так как сообщения, отличные от 5701 и 5703, могут быть возвращены.You should not, however, ignore a SQL_SUCCESS_WITH_INFO return code because messages other than 5701 or 5703 may be returned. Например, если драйвер подключается к серверу, на котором выполняется экземпляр SQL ServerSQL Server с устаревшими хранимыми процедурами каталога, одна из ошибок, возвращаемых через SQLGetDiagRec после SQL_SUCCESS_WITH_INFO:For example, if a driver connects to a server running an instance of SQL ServerSQL Server with outdated catalog stored procedures, one of the errors returned through SQLGetDiagRec after a SQL_SUCCESS_WITH_INFO is:

Функция обработки ошибок приложения для SQL ServerSQL Server подключений должна вызывать SQLGetDiagRec до тех пор, пока не вернет SQL_NO_DATA.The error handling function of an application for SQL ServerSQL Server connections should call SQLGetDiagRec until it returns SQL_NO_DATA. Затем он должен работать с любыми сообщениями, кроме тех, с pfNative кодом 5701 или 5703.It should then act on any messages other than the ones with a pfNative code of 5701 or 5703.

ДокументацияDocumentation

КомпонентыFeatures

  • Пользовательские поставщики хранилища ключейCustom Keystore Providers
  • Классификация данныхData Classification
  • Ключевые слова и атрибуты строки подключения и имени DSNDSN and Connection String Keywords and Attributes
  • SQL Server Native Client (доступные функции, кроме OLEDB, также применимы к ODBC Driver for SQL Server)SQL Server Native Client (the features available also apply, without OLEDB, to the ODBC Driver for SQL Server)
  • Использование Always EncryptedUsing Always Encrypted
  • Использование Azure Active DirectoryUsing Azure Active Directory
  • Использование разрешения IP-адресов прозрачной сетиUsing Transparent Network IP Resolution
  • Using XA Transactions (Использование транзакций XA)Using XA Transactions

Linux и macOSLinux and macOS

  • Установка драйвера в LinuxInstalling the driver on Linux
  • Установка драйвера в macOSInstalling the driver on macOS
  • Подключение к SQL ServerConnecting to SQL Server
  • Подключение с помощью bcpConnecting with bcp
  • Соединение с помощью sqlcmdConnecting with sqlcmd
  • Трассировка доступа к даннымData Access Tracing
  • Часто задаваемые вопросыFrequently Asked Questions
  • Установка диспетчера драйверовInstalling the Driver Manager
  • Известные проблемыKnown Issues
  • Указания по программированиюProgramming Guidelines
  • Заметки о выпускеRelease Notes
  • Поддержка высокого уровня доступности и аварийного восстановленияSupport for High Availability and Disaster Recovery
  • Использование встроенной проверки подлинности (Kerberos)Using Integrated Authentication (Kerberos)

WindowsWindows

  • Образец асинхронного выполнения (метод уведомления)Asynchronous Execution (Notification Method) Sample
  • Устойчивость подключения в драйвере ODBC в WindowsConnection Resiliency in the Windows ODBC Driver
  • Организация пулов соединений с учетом драйвераDriver-Aware Connection Pooling
  • Изменения в возможностях и работеFeatures and Behavior Changes
  • Заметки о выпуске ODBC для SQL Server в WindowsRelease Notes for ODBC to SQL Server on Windows
  • Системные требования, установка и файлы драйвераSystem Requirements, Installation, and Driver Files

Драйвер Microsoft ODBC Driver 13.1 for SQL Server в WindowsMicrosoft ODBC Driver 13.1 for SQL Server on Windows

Драйвер ODBC 13.1 для SQL Server содержит все функции предыдущей версии (11) и добавляет поддержку проверки подлинности Always Encrypted и Azure Active Directory при использовании в сочетании с Microsoft SQL Server 2016.The ODBC Driver 13.1 for SQL Server contains all the functionality of the previous version (11) and adds support for Always Encrypted and Azure Active Directory authentication when used in conjunction with Microsoft SQL Server 2016.

Функция Always Encrypted позволяет клиентам шифровать конфиденциальные данные в клиентских приложениях, не раскрывая ключи шифрования для SQL Server.Always Encrypted allows clients to encrypt sensitive data inside client applications and never reveal the encryption keys to SQL Server. Драйвер с поддержкой Always Encrypted, установленный на клиентском компьютере, реализует это за счет автоматического шифрования и расшифровки конфиденциальных данных в клиентском приложении SQL Server.An Always Encrypted enabled driver installed on the client computer achieves this by automatically encrypting and decrypting sensitive data in the SQL Server client application. Драйвер шифрует данные из конфиденциальных столбцов перед их передачей в SQL Server и автоматически переписывает запросы, чтобы сохранить семантику приложения.The driver encrypts the data in sensitive columns before passing the data to SQL Server, and automatically rewrites queries so that the semantics to the application are preserved. Аналогичным образом драйвер прозрачно расшифровывает данные, хранящиеся в столбцах зашифрованной базы данных, которые содержатся в результатах запроса.Similarly, the driver transparently decrypts data stored in encrypted database columns that are contained in query results. Дополнительные сведения см. в статье Использование функции Always Encrypted с драйвером ODBC.For more information, see Using Always Encrypted with the ODBC Driver.

Azure Active Directory позволяет пользователям, администраторам баз данных и приложениям использовать проверку подлинности Azure Active Directory в качестве механизма подключения к Базе данных SQL Microsoft Azure и Microsoft SQL Server 2016 с помощью удостоверений в Azure Active Directory (Azure AD).Azure Active Directory allows users, DBA’s, and application programmers to use Azure Active Directory authentication as a mechanism of connecting to Microsoft Azure SQL Database and Microsoft SQL Server 2016 by using identities in Azure Active Directory (Azure AD). Дополнительные сведения см. в статьях Using Azure Active Directory with the ODBC Driver (Использование Azure Active Directory с драйвером ODBC) и Use Azure Active Directory Authentication for authentication with SQL (Использование аутентификации Azure Active Directory для аутентификации с помощью SQL).For more information, see Using Azure Active Directory with the ODBC Driver, and Connecting to SQL Database or SQL Data Warehouse By Using Azure Active Directory Authentication.

Подключение к MySQL с помощью драйвера ODBC для MySQLConnect to MySQL with the MySQL ODBC driver

Драйверы ODBC не приводятся в раскрывающемся списке источников данных.ODBC drivers aren’t listed in the drop-down list of data sources. Чтобы подключиться с помощью драйвера ODBC, сначала выберите поставщик данных .NET Framework для ODBC в качестве источника данных на странице Выбор источника данных или Выбор назначения.To connect with an ODBC driver, start by selecting the .NET Framework Data Provider for ODBC as the data source on the Choose a Data Source or Choose a Destination page. Этот поставщик служит оболочкой для драйвера ODBC.This provider acts as a wrapper around the ODBC driver.

Ниже показан экран, который появляется сразу после выбора поставщика данных .NET Framework для ODBC.Here’s the generic screen that you see immediately after selecting the .NET Framework Data Provider for ODBC.

Указываемые параметры (драйвер ODBC для MySQL)Options to specify (MySQL ODBC Driver)

Примечание

Параметры подключения для этого поставщика данных и драйвера ODBC одинаковы независимо от того, является ли сервер MySQL источником или назначением.The connection options for this data provider and ODBC driver are the same whether MySQL is your source or your destination. Таким образом, на страницах Выбор источника данных и Выбор назначения мастера отображаются одинаковые параметры.That is, the options you see are the same on both the Choose a Data Source and the Choose a Destination pages of the wizard.

Чтобы подключиться к MySQL с помощью драйвера ODBC для MySQL, соберите строку подключения, используя указанные ниже параметры и их значения.To connect to MySQL with the MySQL ODBC driver, assemble a connection string that includes the following settings and their values. Полный формат строки подключения приведен после списка параметров.The format of a complete connection string immediately follows the list of settings.

Совет

Вы можете получить помощь в построении строки подключения.Get help assembling a connection string that’s just right. Кроме того, вместо указания строки подключения вы можете предоставить существующее имя DSN (имя источника данных) или создать новое.Or, instead of providing a connection string, provide an existing DSN (data source name) or create a new one. Дополнительные сведения об этих возможностях см. в разделе Подключение к источнику данных ODBC.For more info about these options, see Connect to an ODBC Data Source.

ДрайверDriverИмя драйвера ODBC.The name of the ODBC driver.

ServerServerИмя сервера MySQL.The name of the MySQL server.

База данныхDatabaseИмя базы данных MySQL.The name of the MySQL database.

UID и PWD UID and PWD Идентификатор пользователя и пароль для подключения.The user id and password to connect.

Ввод строки подключенияEnter the connection string

Введите строку подключения в поле ConnectionString либо введите имя DSN в поле Dsn на странице Выбор источника данных или Выбор назначения.Enter the connection string in the ConnectionString field, or enter the DSN name in the Dsn field, on the Choose a Data Source or Choose a Destination page. После того как вы введете строку подключения, мастер проанализирует ее и отобразит отдельные свойства и их значения в списке.After you enter the connection string, the wizard parses the string and displays the individual properties and their values in the list.

В приведенном ниже примере используется следующая строка подключения:The following example uses this connection string.

Ниже показан экран, который появляется после ввода строки подключения.Here’s the screen that you see after entering the connection string.

ODBC: что это такое?

ODBC – это система программных драйверов, использующихся для связи языков программирования с хранилищами данных. Это свободно распространяемая система с открытым исходным кодом, которая создана в 1992 году в попытке стандартизировать способы связи, такие как функции и настройки, между языками программирования и языками запросов к базам данных (стандартизация SQL).

ODBC работает как двойной интерфейс или коннектор: во-первых, как интерфейс от системы языка программирования к ODBC-системе, и во-вторых, как интерфейс от ODBC-системы к системе хранения данных. Таким образом, для ODBC требуется драйвер «язык программирования – ODBC» (например, библиотека PHP-ODBC ) и драйвер «ODBC – система хранения данных» (например, библиотека MySQL-ODBC). Это в дополнение к самой ODBC-системе, которая управляет конфигурациями источников данных и позволяет менять источники данных и языки программирования.

ODBC Connector

MySQL ODBC drivers provide access to a MySQL database in a heterogeneous environment using the industry standard Open Database Connectivity (ODBC) API. MySQL Connector/ODBC provides both driver-manager based and native interfaces to the MySQL database, with the full support of MySQL functionality, including stored procedures, transactions and, with Connector/ODBC 5.1 and higher, full Unicode compliance. The following section describes how to install, configure, and develop database applications using MySQL Connector/ODBC in Windows, Linux, Mac OS X, and Unix platforms

Windows

Before installing the Connector/ODBC drivers on Windows :

  • Make sure you have the Microsoft Visual C++ 2010 Redistributable Package installed on your system. Download the latest version from Microsoft Download Center.

Binary or Source Installation Method :
You can install the Connector/ODBC drivers using two different methods, binary installation or source installation. The binary method is easy which is a bundle of necessary libraries and other files pre-built, with an installer program. The source installation method is important where you want to customize or modifies the installation process or for those platforms where a binary installation package is not available.

Now follow the following steps :
Step -1:
Double click the installer (here it is ‘MySQL-connector-odbc-5.3.2-win32.msi’)

Click on ‘Run’.
Step -2:
This is the Setup Wizard for MySQL Connector/ODBC 5.3, Click ‘Next’.

Step -3:
License agreement : Read the license agreement, either accept or deny.

Accept the terms of the license agreement.
Step -4:
Select ‘Typical’, ‘Complete’ or ‘Custom’ as per your requirement.

Select ‘Typical’ and click ‘Next’.
Step -5:
Now the wizard is ready to begin the installation. Click on ‘Install’.

Step -6:
Click on ‘Finish’ to complete the process.

The installation process has completed, now we will configure the ODBC connections.
Step-1: On the Start menu (windows 7), choose Control Panel\System and Security\Administrative Tools, and then click Data Sources (ODBC).

Step-2: Click on ‘add ‘ and select MySQL ODBC 5.3 ANSI Driver

Step-3: Now you need to configure the specific fields for the DSN you are creating through the Connection Parameters dialog.

  • Data Source Name : Input a valid name of the data source to access.
  • Description : Input some text to identify the connection.
  • TCP/IP Server : Input the name of the MySQL server host to access. By default, it is localhost.
  • User: Input the user name to use for this connection.
  • Password: Input the corresponding password for this connection.
  • Database: The database pop-up should automatically populate with the list of databases that the user has permissions to access.
  • Port: To communicate over a different TCP/IP port than the default (3306).

Step-4: Now input the valid data in specific fields and click on ‘Test’ button to test the connection.

Step-5: You can configure a number of options for a specific DSN by using the ‘Details’ button.

To use Secure Sockets Layer (SSL) when communicating with MySQL server you must specifiy the following additional information.

Example: Using Connector/ODBC with Microsoft Word, Excel or Access

You can use Microsoft Excel, Word to access information from a MySQL database using ODBC. Within Microsoft Excel or Word there are facilities to import data from MySQL database. See the following example.
Step-1: Be sure that your MySQL server is running. Here we are using MySQL 5.6.

Step-2: Create a new worksheet. Here we are using Microsoft Office Excel 2007.

Step-3: From the Data menu, click on ‘From other sources’ then click on ‘Data Connection Wizard’, the following window will come :

Select ‘ODBC DSN’ and Click ‘Next’
Step-4: From ODBC data sources select ‘MySQL’ and click ‘Next’

Step-5: Now select databases and tables.

Step-6: Let select database ‘sakila’ and ‘customer_list’ table and click ‘Next’.

Step-7: Input a name and description for your new Data Connection, and press ‘Finish’ to save.

Step-8: Select how you want to view this data in your workbook (e.g. Table, PivotTable Report etc).

Let select ‘Table’.
Output (partial data):

Previous:
MySQL Connector and APIs IntroductionNext:
MySQL Python Connector

MySQL ODBC Driver Resources:

Take a look at some of our most popular articles from our knowledge base:

  • Connect to and Query MySQL in QlikView over ODBC
  • Create Data Visualizations in Cognos BI with MySQL
  • Create an SAP BusinessObjects Universe on the CData ODBC Driver for MySQL
  • Connect to MySQL as a Linked Server
  • Extract, Transform, and Load MySQL in Informatica PowerCenter
  • DataBind Controls to MySQL in C++Builder
  • Use the CData ODBC Driver for MySQL from SharePoint Excel Services
  • Update MySQL with a Microsoft Access Linked Table

For more articles and technical content related to MySQL ODBC Driver, please visit our online knowledge base.

Универсальная связь

Рассмотрим построение Web-приложений, которые можно развернуть в любом месте (примерами могут служить Drupal, WordPress или Joomla). Часто они строятся с использованием одной базы данных (например, MySQL) с ее специфическими функциями (например, ), а затем тщательно перерабатываются для другой базы данных (например, PostgreSQL) с другими функциями (например, ). При использовании ODBC это лишнее, так как для перенастройки достаточно инициализации приложения, и функции ODBC индифферентны к системе базы данных.

Следует помнить, однако, что хотя все системы управления базами данных поддерживают стандартизованный SQL, иногда они содержат также собственные расширения. Вот почему преобразовать существующее приложение PHP-MySQL, PHP-PostgreSQL или PHP-MS-SQL в приложение PHP-ODBC не так просто. Поэтому, создавая новое приложение, нужно строго придерживаться стандартизированного SQL (или самых распространенных расширений SQL).

Как уже говорилось, ODBC можно использовать и для подключения к электронной таблице. Как и в случае баз данных, это делается с помощью коннектора. Их много – как с открытым исходным кодом, так и фирменных. Примером может служить Microsoft Office для Windows, который содержит ODBC-коннекторы для таблиц Excel. Возможно, работать с электронными таблицами с помощью ODBC весьма неудобно, и гораздо проще, наверное, преобразовать простую электронную таблицу в таблицу базы данных. Однако когда установлено ODBC-соединение с таблицей, его можно рассматривать как соединение с базой данных – те же функции ODBC PHP, но с SQL-подобным языком и стандартными формулами электронной таблицы Excel.

Заключение

ODBC может с успехом применяться для максимально универсальной связи. Это повышает эффективность разработки и позволяет расширять приложения для работы с новыми формами данных, такими как связанные данные на базе Web. Однако у этого подхода есть свои недостатки: для достижения универсального подключения нужно тщательно выбрать способ построения SQL-запросов, так как во всех системах управления базами данных можно использовать только подмножество общедоступных команд SQL. Хотелось бы надеяться, что эта статья окажется полезной для начала работы с базами данных через ODBC с использованием языка программирования PHP.

Похожие темы

  • Оригинал статьи (EN)
  • Раздел W3chools, посвященный SQL — полезен как учебник для начинающих и как справочник по SQL. В нем подробно описано то, что стандартизовано, а также то, что работает на той или иной системе управления базами данных. (EN)
  • Раздел W3Schools, посвященный PHP — еще один полезный ресурс для разработчиков, осваивающих PHP, а также для тех PHP-разработчиков, которым требуется справочник по языку.(EN)
  • iODBC.org: обширные сведения по установке и настройке iODBC, а также полезная информация по ODBC и коннекторам для различных СУБД и языков программирования. (EN)
  • unixODBC.org: информация по установке, настройке и драйверам коннекторов для UnixODBC.
  • MySQL.org: СУБД MySQL для разработчиков, которая с января 2010 года входит в семейство Oracle.(EN)
  • Коннектор ODBC MySQL можно загрузить прямо со страницы MySQL.(EN)
  • О драйвере ODBC Microsoft в MSDN и в файлах помощи программы ODBC Data Source Administrator. В этих двух местах можно найти сведения о работе с Access, SQL Server и Excel через ODBC. (EN)
  • PostgreSQL.org: страница СУБД PostgreSQL. (EN)
  • Проект PostgreSQL ODBC Connector: доступен в качестве бесплатного и открытого программного обеспечения. (EN)
  • OpenLink Virtuoso: «универсальный сервер». Обеспечивает Web-хостинг (в том числе с поддержкой языка PHP), базы данных, ODBC-соединения и технологию Semantic Web. OpenLink Software также отвечает за библиотеку с открытым исходным кодом iODBC, которая поставляется в версии open source и в проприетарной версии. (EN)
  • Для Web-серверов, отличных от OpenLink Virtuoso, ознакомьтесь с Apache HTTP Server и Lighttpd Server (EN)
  • PHP.net: все, что связано с PHP. (EN)
  • Подробная информация обо всех функциях PHP ODBC на сайте PHP.net. (EN)
  • LinkedData.org: хороший портал по связыванию открытых данных и Semantic Web. Портал W3C Semantic Web: еще один полезный ресурс.(EN)
  • Стандарты SQL Международной организации по стандартизации.
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector