Установка программ командной строки SQL Server sqlcmd и bcp в Linux Install sqlcmd and bcp the SQL Server command-line tools on Linux
Применимо к: Applies to: SQL Server SQL Server (все поддерживаемые версии) SQL Server SQL Server (all supported versions) — Linux Применимо к: Applies to: SQL Server SQL Server (все поддерживаемые версии) SQL Server SQL Server (all supported versions) — Linux
Ниже приведены инструкции по установке программ командной строки, драйверов ODBC Майкрософт и их зависимостей. The following steps install the command-line tools, Microsoft ODBC drivers, and their dependencies. Пакет mssql-tools содержит следующие компоненты: The mssql-tools package contains:
- sqlcmd — программа командной строки для выполнения запросов; sqlcmd: Command-line query utility.
- bcp — служебная программа для массового импорта и экспорта. bcp: Bulk import-export utility.
Установите программы для своей платформы: Install the tools for your platform:
В этой статье описывается установка программ командной строки. This article describes how to install the command-line tools. Примеры использования sqlcmd или bcp можно найти по ссылкам в конце этой статьи. If you are looking for examples of how to use sqlcmd or bcp, see the links at the end of this topic.
Установка средств в RHEL 8 Install tools on RHEL 8
Чтобы установить mssql-tools в Red Hat Enterprise Linux, выполните указанные ниже действия. Use the following steps to install the mssql-tools on Red Hat Enterprise Linux.
Перейдите в режим суперпользователя. Enter superuser mode.
Скачайте файл конфигурации репозитория Microsoft Red Hat. Download the Microsoft Red Hat repository configuration file.
Выйдите из режима суперпользователя. Exit superuser mode.
Если установлена предыдущая версия mssql-tools, удалите все старые пакеты unixODBC. If you had a previous version of mssql-tools installed, remove any older unixODBC packages.
Чтобы установить mssql-tools с помощью пакета разработчика unixODBC, выполните приведенные ниже команды. Run the following commands to install mssql-tools with the unixODBC developer package.
Чтобы произвести обновление до последней версии mssql-tools, выполните следующие команды: To update to the latest version of mssql-tools run the following commands:
Необязательно: Добавьте путь /opt/mssql-tools/bin/ в переменную среды PATH в оболочке bash. Optional: Add /opt/mssql-tools/bin/ to your PATH environment variable in a bash shell.
Чтобы программы sqlcmd и bcp были доступны из оболочки bash в рамках сеансов входа в систему, измените переменную среды PATH в файле
/.bash_profile с помощью следующей команды: To make sqlcmd/bcp accessible from the bash shell for login sessions, modify your PATH in the
/.bash_profile file with the following command:
Чтобы программы sqlcmd и bcp были доступны из оболочки bash в рамках интерактивных сеансов и сеансов без входа в систему, измените переменную среды PATH в файле
/.bashrc с помощью следующей команды: To make sqlcmd/bcp accessible from the bash shell for interactive/non-login sessions, modify the PATH in the
/.bashrc file with the following command:
Установка средств в Ubuntu 16.04 Install tools on Ubuntu 16.04
Чтобы установить mssql-tools в Ubuntu, выполните указанные ниже действия. Use the following steps to install the mssql-tools on Ubuntu.
Ubuntu 18.04 поддерживается, начиная с SQL Server 2019 с накопительным пакетом обновления 3 (CU3). Ubuntu 18.04 is supported starting with SQL Server 2019 CU3. Если вы используете Ubuntu 18.04, измените путь к репозиторию с /ubuntu/16.04 на /ubuntu/18.04 . If you are using Ubuntu 18.04, change the repository path from /ubuntu/16.04 to /ubuntu/18.04 .
Импортируйте открытые ключи GPG из репозитория. Import the public repository GPG keys.
Зарегистрируйте репозиторий Ubuntu для Майкрософт. Register the Microsoft Ubuntu repository.
Обновите список источников и выполните команду установки с помощью пакета разработчика unixODBC. Update the sources list and run the installation command with the unixODBC developer package.
Чтобы произвести обновление до последней версии mssql-tools, выполните следующие команды: To update to the latest version of mssql-tools run the following commands:
Необязательно: Добавьте путь /opt/mssql-tools/bin/ в переменную среды PATH в оболочке bash. Optional: Add /opt/mssql-tools/bin/ to your PATH environment variable in a bash shell.
Чтобы программы sqlcmd и bcp были доступны из оболочки bash в рамках сеансов входа в систему, измените переменную среды PATH в файле
/.bash_profile с помощью следующей команды: To make sqlcmd/bcp accessible from the bash shell for login sessions, modify your PATH in the
/.bash_profile file with the following command:
Чтобы программы sqlcmd и bcp были доступны из оболочки bash в рамках интерактивных сеансов и сеансов без входа в систему, измените переменную среды PATH в файле
/.bashrc с помощью следующей команды: To make sqlcmd/bcp accessible from the bash shell for interactive/non-login sessions, modify the PATH in the
/.bashrc file with the following command:
Установка средств в SLES 12 Install tools on SLES 12
Чтобы установить mssql-tools в SUSE Linux Enterprise Server, выполните указанные ниже действия. Use the following steps to install the mssql-tools on SUSE Linux Enterprise Server.
Добавьте репозиторий Microsoft SQL Server в Zypper. Add the Microsoft SQL Server repository to Zypper.
Установите mssql-tools с помощью пакета разработчика unixODBC. Install mssql-tools with the unixODBC developer package.
Чтобы произвести обновление до последней версии mssql-tools, выполните следующие команды: To update to the latest version of mssql-tools run the following commands:
Необязательно: Добавьте путь /opt/mssql-tools/bin/ в переменную среды PATH в оболочке bash. Optional: Add /opt/mssql-tools/bin/ to your PATH environment variable in a bash shell.
Чтобы программы sqlcmd и bcp были доступны из оболочки bash в рамках сеансов входа в систему, измените переменную среды PATH в файле
/.bash_profile с помощью следующей команды: To make sqlcmd/bcp accessible from the bash shell for login sessions, modify your PATH in the
/.bash_profile file with the following command:
Чтобы программы sqlcmd и bcp были доступны из оболочки bash в рамках интерактивных сеансов и сеансов без входа в систему, измените переменную среды PATH в файле
/.bashrc с помощью следующей команды: To make sqlcmd/bcp accessible from the bash shell for interactive/non-login sessions, modify the PATH in the
/.bashrc file with the following command:
Установка средств в macOS Install tools on macOS
В macOS доступна предварительная версия программ sqlcmd и bcp. A preview of sqlcmd and bcp is now available on macOS. Дополнительные сведения см. в объявлении о выпуске. For more information, see the announcement.
Установите программу Homebrew, если ее еще нет: Install Homebrew if you don’t have it already:
- /usr/bin/ruby -e «$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)»
Чтобы установить средства для Mac El Capitan и Sierra, используйте следующие команды: To install the tools for Mac El Capitan and Sierra, use the following commands:
Docker Docker
Если SQL Server выполняется в контейнере Docker, программы командной строки SQL Server уже включены в образ контейнера SQL Server в Linux. If you run SQL Server in a Docker container, the SQL Server command-line tools are already included in the SQL Server Linux container image. Если подключиться к запущенному контейнеру с помощью интерактивной оболочки bash, можно запускать программы локально. If you attach to a running container with an interactive bash shell, you can run the tools locally.
Автономная установка Offline installation
Если компьютер Linux не имеет доступа к онлайн-хранилищам, которые используются в предыдущих разделах, вы можете загрузить файлы пакетов напрямую. If your Linux machine does not have access to the online repositories used in the previous sections, you can download the package files directly. Эти пакеты находятся в репозитории Майкрософт по адресу https://packages.microsoft.com. These packages are located in the Microsoft repository, https://packages.microsoft.com.
После успешного выполнения действий по установке, указанных в предыдущих разделах, загружать или вручную устанавливать указанные ниже пакеты не требуется. If you successfully installed with the steps in the previous sections, you do not need to download or manually install the package(s) below. Это нужно только для автономных сценариев. This is only for the offline scenario.
Сначала найдите и скопируйте пакет mssql-tools для своего дистрибутива Linux: First, locate and copy the mssql-tools package for your Linux distribution:
Дистрибутив Linux Linux distribution | Расположение пакета mssql-toolsmssql-tools package location |
---|---|
Red Hat Red Hat | https://packages.microsoft.com/rhel/7.3/prod |
SLES SLES | https://packages.microsoft.com/sles/12/prod |
Ubuntu 16.04 Ubuntu 16.04 | https://packages.microsoft.com/ubuntu/16.04/prod/pool/main/m/mssql-tools |
Кроме того, найдите и скопируйте пакет msodbcsql, который является зависимостью. Also locate and copy the msodbcsql package, which is a dependency. Пакет msodbcsql также имеет зависимость от unixODBC-devel (Red Hat и SLES) или от unixodbc-dev (Ubuntu). The msodbcsql package also has a dependency on either unixODBC-devel (Red Hat and SLES) or unixodbc-dev (Ubuntu). Расположение пакетов msodbcsql приведено в следующей таблице: The location of the msodbcsql packages are listed in the following table:
Дистрибутив Linux Linux distribution | Расположение пакетов ODBC ODBC packages location |
---|---|
Red Hat Red Hat | https://packages.microsoft.com/rhel/8/prod |
SLES SLES | https://packages.microsoft.com/sles/12/prod |
Ubuntu 16.04 Ubuntu 16.04 | msodbcsqlmsodbcsql unixodbc-devunixodbc-dev |
Переместите скачанные пакеты на компьютер Linux. Move the downloaded packages to your Linux machine. Если для скачивания пакетов вы использовали другой компьютер, переместить пакеты на компьютер Linux можно с помощью команды scp. If you used a different machine to download the packages, one way to move the packages to your Linux machine is with the scp command.
Установите пакеты. Установите пакеты mssql-tools и msodbc. Install the and packages: Install the mssql-tools and msodbc packages. Если возникают ошибки зависимостей, игнорируйте их до следующего шага. If you get any dependency errors, ignore them until the next step.
Платформа Platform | Команды для установки пакетов Package install commands |
---|---|
Red Hat Red Hat | sudo yum localinstall msodbcsql- .rpm sudo yum localinstall mssql-tools- .rpm |
SLES SLES | sudo zypper install msodbcsql- .rpm sudo zypper install mssql-tools- .rpm |
Ubuntu Ubuntu | sudo dpkg -i msodbcsql_ .deb sudo dpkg -i mssql-tools_ .deb |
Разрешите отсутствующие зависимости. На этом этапе зависимости могут отсутствовать. Resolve missing dependencies: You might have missing dependencies at this point. Если это не так, пропустите этот шаг. If not, you can skip this step. В некоторых случаях необходимо найти и установить зависимости вручную. In some cases, you must manually locate and install these dependencies.
Для пакетов RPM проверить требуемые зависимости можно с помощью следующих команд: For RPM packages, you can inspect the required dependencies with the following commands:
Для пакетов Debian, если у вас есть доступ к утвержденным репозиториям, содержащим эти зависимости, самым простым решением является использование команды apt-get. For Debian packages, if you have access to approved repositories containing those dependencies, the easiest solution is to use the apt-get command:
Эта команда также завершает установку пакетов SQL Server. This command completes the installation of the SQL Server packages as well.
Если эта команда не работает для пакета Debian, проверить требуемые зависимости можно с помощью следующих команд: If this does not work for your Debian package, you can inspect the required dependencies with the following commands:
Дальнейшие действия Next steps
Пример использования sqlcmd для подключения к SQL Server и создания базы данных см. в одном из следующих кратких руководств: For an example of how to use sqlcmd to connect to SQL Server and create a database, see one of the following quickstarts:
Пример использования bcp для массового импорта и экспорта данных см. в статье Массовое копирование данных в SQL Server на Linux. For an example of how to use bcp to bulk import and export data, see Bulk copy data to SQL Server on Linux.