- Настройка в Linux подключения к MariaDB из PHP с помощью ODBC
- ODBC connector
- Установка и подготовка к работе СУБД
- Установка и настройка ODBC
- Функции ODBC и DB2 (PDO_ODBC)
- Введение
- Установка
- Предопределённые константы
- Настройка во время выполнения
- Installing and Configuring the ODBC Driver for Linux¶
- Prerequisites¶
- Operating System¶
- Driver Manager: iODBC or unixODBC¶
- iODBC¶
- unixODBC¶
- Step 1: Verify the Package Signature (RPM or DEB only) — Optional¶
- 1.1: Download and Import the Latest Snowflake Public Key¶
- 1.2: Download the RPM or DEB Driver Package¶
- 1.3: Verify the Signature for the RPM or DEB Driver Package¶
- RPM Package Signature¶
- DEB Package Signature¶
- 1.4: Delete the Old Snowflake Public Key — Optional¶
- Step 2: Install the ODBC Driver¶
- Using yum to Download and Install the Driver¶
- Installing the TGZ File¶
- Installing the RPM Package¶
- Installing the DEB Package¶
- Step 3: Configure the Environment (TGZ Only)В¶
- Configuring with iODBC¶
- Configuring with unixODBC¶
- Step 4: Configure the ODBC Driver¶
- 4.1: simba.snowflake.ini File (Driver Manager and Logging)В¶
- 4.2: odbcinst.ini File (Driver Registration)В¶
- 4.3: odbc.ini File (DSN Entries)В¶
- Step 5: Test the ODBC Driver¶
- Testing with iODBC¶
Настройка в Linux подключения к MariaDB из PHP с помощью ODBC
Использование ODBC в PHP позволит делать SQL-запросы независимо от типа СУБД — это может быть MySQL/MariaDB, MS SQL, Sybase, Oracle, PostgreSQL и так далее. Мы рассмотрим подключение к MariaDB. Предложенная инструкция протестирована на Linux Ubuntu и CentOS.
Наши действия разобьем по шагам:
ODBC connector
Для начала мы должны установить ODBC connector. Нам понадобиться скачать на наш сервер архив, поэтому сначала инсталлируем wget.
а) на CentOS / Red Hat:
yum install wget
б) на Ubuntu / Debian:
apt-get install wget
После установки wget перейдем в каталог /tmp:
Открываем браузер и заходим на страницу загрузки коннекторов MariaDB и выбираем ODBC connector, а также нашу операционную систему, например:
* в данном случае мы загрузим коннектор для CentOS 8.
Ниже на этой же страницы мы увидим ссылку на скачивание нужного нам коннектора. Копируем данную ссылку:
С помощью wget и скопированной ссылки загружаем на сервер коннектор:
tar zxvf mariadb-connector-odbc-*.tar.gz
И копируем библиотеки в каталог /usr/lib64:
cp mariadb-connector-odbc-*-amd64/lib64/mariadb/lib* /usr/lib64/
После скачанный архив и распакованный каталог можно удалить:
rm -rf mariadb-connector-odbc-*
Установка и подготовка к работе СУБД
Для проверки настройки нам нужен сервер баз данных. Если его нет, то установим mariadb-server на тот же сервер, где и развернули ODBC.
а) для CentOS / Red Hat:
yum install mariadb-server
б) для Ubuntu / Debian:
apt-get install mariadb-server
После установки запускаем сервис и настраиваем его на автозапуск:
systemctl enable mariadb —now
Задаем пароль для суперпользователя:
mysqladmin -u root password
Заходим в консоль SQL:
Создаем новую базу данных:
> CREATE DATABASE my_db DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;
* для наших тестов мы создали базу с названием my_db.
Дадим права на подключение и работу с созданной базой данных:
> GRANT ALL PRIVILEGES ON my_db.* TO ‘odbc_user’@’localhost’ IDENTIFIED BY ‘odbc_password’;
* данной командой мы разрешили доступ к базе my_db пользователю odbc_user, который будет подключаться с локального компьютера и паролем odbc_password.
Подключаемся к созданной базе данных:
Создаем простенькую таблицу:
> CREATE TABLE IF NOT EXISTS `users` (
`id` int(10) unsigned NOT NULL auto_increment,
`name` varchar(512) NOT NULL,
`rights` varchar(64) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
* наша созданная таблица будет состоять из 3 столбцов — id, name и rights.
Добавим 3 строки в нашу таблицу:
> INSERT INTO users (`name`, `rights`) VALUES (‘Дмитрий’, ‘admin’), (‘Оля’, ‘superuser’), (‘Антон’ ,’operator’);
Готово. Теперь выходим из sql-оболочки:
Установка и настройка ODBC
Устанавливаем сам ODBC.
а) для CentOS / Red Hat:
yum install unixODBC
б) для Ubuntu / Debian:
apt-get install unixodbc odbcinst
Открываем конфигурационный файл:
Проверяем наличие следующей записи (если ее нет, добавляем):
.
[MariaDB]
Description = ODBC for MariaDB
Driver = /usr/lib/libmaodbc.so
Driver64 = /usr/lib64/libmaodbc.so
FileUsage = 1
.
* в данном примере описано подключение к СУБД с драйвером MariaDB и путем до файла с библиотекой (отдельно для 32- и 64-разрядной версии).
Добавляем DSN для подключения к нашему серверу и базе, которую создавали на предыдущем этапе:
[ODBC]
Driver = MariaDB
USER = odbc_user
PASSWORD = odbc_password
Server = 127.0.0.1
Database = my_db
Port = 3306
- ODBC — произвольное название для нашего подключения.
- Driver — драйвер, который мы будем использовать. Его мы описали в файле /etc/odbcinst.ini.
- USER — пользователь, под которым будем подключаться к базе. Используем данные для ранее созданной учетной записи в mariadb.
- PASSWORD — пароль для созданного ранее пользователя, под которым мы будем подключаться к базе.
- Server — сервер баз данных. В нашем примере локальный сервер.
- Database — имя созданной базы данных.
- Port — порт, на котором слушает сервер. 3306 используется по умолчанию для MariaDB.
Пробуем подключиться к базе с использованием ODBC:
* где ODBC — название для подключения, которое мы задали на предыдущем шаге.
Мы должны увидеть командную строку для ввода команд sql — пробуем получить данные из нашей таблицы users:
Источник
Функции ODBC и DB2 (PDO_ODBC)
Введение
PDO_ODBC — драйвер, реализующий интерфейс PHP Data Objects (PDO) для доступа к базам данных через драйвер ODBC или через библиотеку IBM DB2 Call Level Interface (DB2 CLI). В текущий момент PDO_ODBC поддерживает различные «оттенки» драйверов баз данных: ibm-db2
Поддержка доступа к серверам IBM DB2 Universal Database, Cloudscape и Apache Derby через свободный клиент DB2 express-C.
Поддерживает доступ к базам данных через менеджер драйверов unixODBC и собственные ODBC драйверы баз данных.
Предоставляет опцию компиляции менеджеров драйверов ODBC, которые не поддерживаются PDO_ODBC напрямую.
В Windows php_pdo_odbc.dll должен быть включён как модуль в php.ini . Он собирается с участием Windows ODBC Driver Manager, поэтому PHP может подключаться к любой базе данных, определённой как System DSN.
Установка
Модуль PDO_ODBC включён в исходный код PHP. Вы можете скомпилировать модуль как статический или разделяемый, используя следующий синтаксис configure. ibm_db2
Если вы не укажете директорию установки библиотек и заголовочных файлов DB2, configure будет искать их в /home/db2inst1/sqllib .
Предопределённые константы
Перечисленные ниже константы определены данным драйвером и будут доступны только в случае, если PHP был собран с поддержкой этого модуля, или данный модуль был динамически загружен во время выполнения. Вдобавок, эти зависимые от драйвера константы должны быть использованы только совместно с этим драйвером. Использование атрибутов, специфичных для некоторого драйвера с другим драйвером может вызвать неожиданное поведение. Если ваш код выполняется с несколькими драйверами, то можно использовать функцию PDO::getAttribute() для получения атрибута PDO::ATTR_DRIVER_NAME для проверки драйвера.
PDO::ODBC_ATTR_USE_CURSOR_LIBRARY ( int )
Этот параметр определяет, используется ли библиотека курсоров ODBC. Библиотека курсоров ODBC поддерживает некоторые дополнительные особенности ODBC (например блочные прокручиваемые курсоры), которые могут не реализовываться драйвером. Поддерживаются следующие значения:
PDO::ODBC_SQL_USE_IF_NEEDED (по умолчанию): использовать библиотеку курсоров ODBC если необходимо.
PDO::ODBC_SQL_USE_DRIVER : никогда не использовать библиотеку курсоров ODBC.
PDO::ODBC_SQL_USE_ODBC : всегда использовать библиотеку курсоров ODBC.
PDO::ODBC_ATTR_ASSUME_UTF8 ( bool )
Только для Windows. Если true , то данные в кодировке UTF-16 ( CHAR , VARCHAR и LONGVARCHAR ) будут сконвертированны в UTF-8 при чтении или записи. Если false (по умолчанию), преобразование кодировки символов может быть выполнено драйвером.
Настройка во время выполнения
Поведение этих функций зависит от установок в php.ini .
Имя | По умолчанию | Место изменения | Список изменений |
---|---|---|---|
pdo_odbc.connection_pooling | «strict» | PHP_INI_ALL | |
pdo_odbc.db2_instance_name | NULL | PHP_INI_SYSTEM | Эта возможность устарела и будет обязательно удалена в будущем. |
Для подробного описания констант PHP_INI_*, обратитесь к разделу Где могут быть установлены параметры конфигурации.
Краткое разъяснение конфигурационных директив.
Нужно ли объединять соединения ODBC. Может быть «strict» , «relaxed» или «off» (аналогично «» ). Параметр определяет как строго менеджер соединений должен сравнивать параметры соединений для выбора, создавать новое соединение или возвращать уже существующее. По умолчанию рекомендуется использовать strict , что означает, что сохранённое соединение будет возвращаться только, если все параметры точно совпадают. relaxed приведёт к тому, что закешированное соединение будет возвращено, если параметры схожи. Это приведёт к более активному использованию кеша, но может привести к утечке информации о соединении (к примеру) между виртуальными хостами.
Эту настройку можно изменить только в php.ini и воздействует на все процессы; все модули, загруженные в процесс и использующие те же библиотеки ODBC будут зависеть от этой настройки, включая Унифицированный модуль ODBC.
Значение relaxed не должно использоваться на общем хостинге в целях безопасности.
Если у вас нет очень серьёзного повода использовать значение, отличное от strict — не меняйте его.
Если вы скомпилировали PDO_ODBC с использованием db2 , эта опция установит значение переменной окружения DB2INSTANCE в системах Linux и UNIX, равным выбранному имени экземпляра DB2. Это позволяет PDO_ODBC определить местоположение библиотек DB2 и произвести соединение с каталогом базы данных DB2.
Источник
Installing and Configuring the ODBC Driver for Linux¶
Linux uses named data sources (DSNs) for connecting ODBC-based client applications to Snowflake. You can choose to install the ODBC driver using the TGZ file, RPM package, or DEB package provided in the Snowflake Client Repository.
In this Topic:
Prerequisites¶
Operating System¶
For a list of the operating systems supported by Snowflake clients, see Operating System Support .
Driver Manager: iODBC or unixODBC¶
A driver manager is required to manage communication between Snowflake and the ODBC driver. The driver supports using either iODBC or unixODBC as the driver manager.
iODBC¶
If iODBC is not installed on CentOS, as sudo , execute the following command:
unixODBC¶
unixODBC provides the odbcinst and isql command line utilities used to install, configure, and test the driver. To verify whether unixODBC is installed, execute the following commands:
If unixODBC is not installed:
As sudo , execute the following commands:
Verify the directory where odbcinst expects the odbcinst.ini and odbc.ini files to be located:
The location should be /etc .
Step 1: Verify the Package Signature (RPM or DEB only) — Optional¶
If you are installing the ODBC driver by using yum or the TGZ file , skip this step.
If you are installing the ODBC driver using the RPM or DEB package and wish to verify the package signature before installation, perform the following tasks:
1.1: Download and Import the Latest Snowflake Public Key¶
To download and import the key from the public keyserver:
For , specify one of the following key IDs:
ODBC Driver Version
2.22.1 and higher
2.18.2 through 2.22.0
If this command fails with the following error:
then specify that you want to use port 80 for the keyserver:
1.2: Download the RPM or DEB Driver Package¶
Download the package from the Snowflake Client Repository. For details, see Downloading the ODBC Driver .
1.3: Verify the Signature for the RPM or DEB Driver Package¶
RPM Package Signature¶
Verify the key was imported successfully:
The command should display the Snowflake key.
Verify the signature:
If rpm does not have the GPG key that you imported, the command will report that the signatures are not OK and will produce a NOKEY warning:
If this occurs, run the following commands to export the GPG key, import the key into rpm , and verify the signature again:
where is the ID for the key that you installed in 1.1: Download and Import the Latest Snowflake Public Key .
DEB Package Signature¶
Install the package signature verification tool:
Import the public key to the keyring:
where is the ID for the key that you installed in 1.1: Download and Import the Latest Snowflake Public Key .
Configure a policy for the key. For details, see /usr/share/doc/debsig-verify . The policy must be stored in the following directory:
where is the ID for the key that you installed in 1.1: Download and Import the Latest Snowflake Public Key .
Store the policy in a file named policy_name .pol , where policy_name is your name for the policy. For the policy name, you can use any text string, however the string cannot contain blank spaces.
Here is a sample policy file for a key with the ID 37C7086698CB005C:
Verify the signature:
By default, the dpkg package signature verification tool does not check the signature when you install the package. If you want to verify the signature every time you run dpkg, remove the —no-debsig line in the /etc/dpkg/dpkg.cfg file.
1.4: Delete the Old Snowflake Public Key — Optional¶
Your local environment can contain multiple GPG keys; however, for security reasons, Snowflake periodically rotates the public GPG key. As a best practice, we recommend deleting the existing public key after confirming that the latest key works with the latest signed package.
To delete the key:
Step 2: Install the ODBC Driver¶
Install the driver using one of the following approaches:
Using yum to Download and Install the Driver¶
With version 2.21.1 of the ODBC Driver (and later versions), you can use yum to download and install the driver.
To download and install the Snowflake ODBC driver for Linux using yum :
Create a file named /etc/yum.repos.d/snowflake-odbc.repo , and add the following text to the file:
where VERSION is the version of the driver (for example, 2.24.0) and GPG_KEY_ID is one of the following key IDs:
ODBC Driver Version
2.22.1 and higher
In the settings above, baseurl and gpgkey point to the Snowflake Client Repository on AWS S3. If you want to use the mirror on Azure Blob instead, change the hostname to https://sfc-repo.azure.snowflakecomputing.com/ :
Run the following command to install the driver:
Installing the TGZ File¶
To install the Snowflake ODBC driver for Linux using the TGZ file that you downloaded earlier .
Copy the downloaded file ( snowflake_linux_x8664_odbc- version .tgz ) to a working directory.
Extract the files from the .tar file:
Copy the resulting snowflake_odbc folder to the directory where you want to install the driver. Make note of this directory. You’ll need the location later in the instructions.
Installing the RPM Package¶
The RPM package requires unixODBC as the driver manager.
To install the Snowflake ODBC driver for Linux using the RPM package that you downloaded earlier , after optionally verifying the package signature , run the following command:
The installation directory is /usr/lib64/snowflake/odbc/ . You’ll need the location later in the instructions.
Installing the DEB Package¶
The DEB package requires unixODBC as the driver manager.
To install the Snowflake ODBC driver for Linux using the DEB package that you downloaded earlier , after optionally verifying the package signature , run the following command:
The command may fail if any required dependencies for the package manager are not installed. If that happens, install them now:
The installation directory is /usr/lib/snowflake/odbc/ . You’ll need the location later in the instructions.
Step 3: Configure the Environment (TGZ Only)В¶
If you installed the ODBC driver using the RPM or DEB package file, skip this step.
If you installed using the TGZ file, configure the environment using the installed driver manager (either iODBC or unixODBC).
Configuring with iODBC¶
In a terminal window, change to the snowflake_odbc directory, and run the following command to install Snowflake ODBC:
This script completes the following steps:
Adds one Snowflake connection to your system-level /etc/odbc.ini file.
Adds the Snowflake driver information to your system-level /etc/odbcinst.ini file.
Adds all certificate authority (CA) certificates required by the Snowflake ODBC driver to your system-level simba.snowflake.ini file.
By running iodbc_setup.sh , you don’t need to set any environment variables.
Alternatively, if you don’t want Snowflake to change your system configurations, add the following environment variables to your shell configuration file (e.g. .profile , .bash_profile ):
Where path is the location of the snowflake_odbc directory. If you have configured other ODBC drivers in your system and plan to add the Snowflake ODBC entries to your existing odbc.ini and odbcinst.ini files in the next step, then point ODBCINI and ODBCINSTINI to the location of those files.
Configuring with unixODBC¶
In a terminal window, change to the snowflake_odbc directory, and run the following command to install Snowflake ODBC:
This script completes the following steps:
Adds a Snowflake connection to your system-level /etc/odbc.ini file.
Adds the Snowflake driver information to your system-level /etc/odbcinst.ini file.
Adds all certificate authority (CA) certificates required by the Snowflake ODBC driver to your system-level simba.snowflake.ini file.
By running unixodbc_setup.sh , you don’t need to set any environment variables.
Alternatively, if you don’t want Snowflake change your system configurations, add the following environment variables to your shell configuration file, e.g. .profile , .bash_profile :
Where path is the location of the snowflake_odbc directory. If you have configured other ODBC drivers in your system and plan to add the Snowflake ODBC entries to your existing odbc.ini and odbcinst.ini files in the next step, then point ODBCSYSINI to the location of those files.
Step 4: Configure the ODBC Driver¶
Configuring the ODBC driver requires adding entries to the following files:
/conf/odbc.ini , if you are using environment variables)
/conf/odbcinst.ini , if you are using environment variables)
Where path is the location of the snowflake_odbc directory.
4.1: simba.snowflake.ini File (Driver Manager and Logging)В¶
Add the following entries to the simba.snowflake.ini file:
path is the location of the snowflake_odbc directory.
driver_manager_path is the location of your driver manager directory:
If your driver manager directory is not included in the LD_LIBRARY_PATH environment variable, specify the full path to the driver manager library here.
Verify that you have write permissions on the log path.
The ANSIENCODING parameter specifies the application’s character encoding. The default is UTF-8 . The parameter is intended for use only by Snowflake; customers should not change the value.
4.2: odbcinst.ini File (Driver Registration)В¶
Add the following entries to the odbcinst.ini file:
Where path is the location of the snowflake_odbc directory.
4.3: odbc.ini File (DSN Entries)В¶
For each DSN, add the following entries to the odbc.ini file:
DSN Name and driver name (SnowflakeDSIIDriver), in the form of = .
Required connection parameters, such as server .
Any additional, optional parameters, such as default role , database , and warehouse .
Parameters are specified in the form of
= . For details about the parameters that can be set for each DSN, see ODBC Configuration and Connection Parameters .
The following example illustrates an odbc.ini file that configures two data sources that use different forms of an account identifier in the server URL:
testodbc1 uses an account identifier that uses an account identifier that specifies the account myaccount in the organization myorganization .
testodbc2 uses the account locator xy12345 as the account identifier.
Note that testodbc2 uses an account in the AWS US West (Oregon) region. If the account is in a different region or if the account uses a different cloud provider, you need to specify additional segments after the account locator .
Note the following:
Both testodbc1 and testodbc2 have default roles.
testodbc2 also has a default database and warehouse.
Step 5: Test the ODBC Driver¶
Test the driver using the installed driver manager (either iODBC or unixODBC).
Testing with iODBC¶
Test the DSNs you created. On the command line, specify the DSN name, user login name, and password, using the following format:
Источник