Что такое odbc linux

Установка MS SQL ODBC Driver под Linux и сборка плагина для Qt 5.9

Несколько дней назад встал вопрос о написании консольного приложения, которое будет работать в Linux CentOS 7 и взаимодействовать с MS SQL Server 2012. Мне очень нравится Qt и я решил, что воспользуюсь им для решения этой задачи. И если под Windows я достаточно быстро настроил необходимое окружение, то под Linux я столкнулся с проблемами, которые очень тяжело было решить с помощью гуглинга. Этому вопросу я посвятил полтора дня. Считаю полезным поделиться своим опытом, возможно кому-то это поможет сэкономить драгоценное время.

Инструменты

Я не хочу тянуть на сервер исходники Qt, для того чтобы собрать плагин и само приложение. Поэтому беру образ CentOS 7 LiveGNOME и устанавливаю его на VirtualBox машину. После делаю полный апдейт, и ставлю VirtualBox Guest Additions.

Скачиваю установщик Qt для Linux x64. Устанавливаю Qt 5.9.1, дополнительно при установке выбираю галочку Source, чтобы получить исходники.

Установка Microsoft ODBC Driver for SQL Server

Согласно инструкции устанавливаю драйвер:

Драйвер нужно установить как на VirtualBox, так и на машину, где будет работать софт.

Сборка Qt плагина QODBC

Следуя инструкции, скачиваем куда-нибудь unixODBC, распаковываем. Теперь нам нужно собрать unixODBC и установить. В документации Qt, а так же в других источниках в основном я встречал примеры, которые предполагают установку unixODBC в /usr/local/unixODBC. Тут дело вкуса конечно, но я буду использовать именно такое расположение. Так же файлы конфигов драйверов я хочу поместить в /usr/local/etc Для этого нужно сконфигурировать unixODBC со следующими параметрами:

Затем собираем и устанавливаем:

Теперь необходимо настроить конфигурацию Microsoft ODBC Driver for SQL Server. Для этого переходим в /usr/local/unixODBC/bin и выполняем:

Если вы устанавливали драйвер как было описано выше, то расположение файла odbcinst.ini будет именно таким. Иначе вам нужно определить свой путь. Все эти действия нужно выполнить и на Virtualbox машине и на рабочей.

Теперь нужно собрать Qt плагин для работы с ODBC драйвером. И с этого момента начинаются проблемы, которые частично связаны с багом, который еще не пофиксили. Для того, чтобы собрать плагин придется применить некоторые костыли. Если у кого-то возникнет более элегантный вариант костыля, пожалуйста напишите в комментариях.

Итак, для сборки в штатных условиях нам нужно выполнить простую процедуру. Переходим в QT_DIR/5.9.1/Src/qtbase/src/plugins/sqldrivers/odbc и выполняем:

Но из-за того, что имеем баг, скорее всего вы получите ошибку:

На отсутствие файла qtsqldrivers-config.pri, можно не обращать внимание, а вот вторая ошибка не даст нам собрать плагин. Чтобы ее избежать нужно закомменитровать в файле odbc.pro строчку:

После этого повторим вызов qmake:

И получим на выходе Makefile. Еще одна проблема с которой я столкнулся это флаги компилятора -Wdate_time и -std=c++1z, которые вызывали ошибку сборки.

Читайте также:  Самая быстрая линукс система

На этот момент я уже потратил много времени, чтобы хоть как-то собрать плагин, поэтому эту проблему я решил жестко, просто открыл сгенерированный Makefile и изменил -std=c++1z на -std=c++11, а флаг -Wdate_time просто удалил. Эти пары флагов встречаются в двух местах. Можно установить более свежий gcc, или может кто-то подскажет есть ли возможность указать для qmake какие-то параметры, чтобы использовать c++11 вместо c++17?

Как бы вы ни поступили, теперь можно выполнить:

Тестовое приложение

Я создал консольное приложение в Qt и написал следующий код для тестирования соединения:

Собираем проект на Virtualbox машине. Запускаем, убеждаемся, что все работает. После этого собираем Release версию программы. Я не буду сейчас описывать процесс деплоя Qt приложений. Возможно это тема для еще одной публикации. Я опишу лишь ключевые моменты.

Источник

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 .

Читайте также:  Linux как посмотреть параметры сети

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.

Читайте также:  Core linux install package

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:

Источник

Оцените статью