Add a connection to Azure SQL Database
Applies to: Visual Studio
Visual Studio for Mac
Visual Studio Code
With Visual Studio, you can connect any of the following to Azure SQL Database by using the Connected Services feature:
- .NET Framework console app
- ASP.NET MVC (.NET Framework)
- ASP.NET Core
- .NET Core (including console app, WPF, Windows Forms, class library)
- .NET Core Worker Role
- Azure Functions
- Universal Windows Platform App
- Xamarin
- Cordova
The connected service functionality adds all the needed references and connection code to your project, and modifies your configuration files appropriately.
This topic applies to Visual Studio on Windows. For Visual Studio for Mac, see Connected services in Visual Studio for Mac.
Prerequisites
- Visual Studio with the Azure workload installed.
- A project of one of the supported types
Connect to Azure SQL Database using Connected Services

- Open your project in Visual Studio.
- In Solution Explorer, right-click the Connected Services node, and, from the context menu, select Add to open the menu of available services.
- Choose SQL Server Database. The Connect to dependency page appears. You should see several options:
- SQL Server Express LocalDB, the built-in SQL database offering installed with Visual Studio
- SQL Server Database on a local container on your machine
- SQL Server Database, a on-premises SQL server on the local network
- Azure SQL database, for the SQL database running as an Azure service
You can reduce cost and simplify early development by starting with a local database. You can migrate to the live service in Azure later by repeating these steps and choosing another option. If you create a database locally that you want to recreate in Azure, you can migrate your database to Azure at that time.

If you want to connect to the Azure service, continue to the next step, or if you aren’t signed in already, sign into your Azure account before continuing. If you don’t have an Azure account, you can sign up for a free trial.

- Select Create New by the green plus sign.
- Fill out the Azure SQL Database: Create new screen, and select Create.

- When the Configure Azure SQL Database screen is displayed, the new database appears in the list. Select the new database in the list, and select Next.

If prompted to set a firewall rules, choose Yes. 
If you click on the three dots next to the dependency you added, you can see various options such as Connect to reopen the wizard and change the connection. You can also click the three dots at the top right of the window to see options to start local dependencies, change settings, and more.Access the connection string
Learn how to store secrets safely by following Safe storage of app secrets in development in ASP.NET Core. In particular, to read the connection string from the secrets store, you can add code as in Read the secret via the configuration API. See also Dependency injection in ASP.NET Core.
Entity Framework migrations
It might be convenient to work with a local data store during early development, but with Entity Framework Core, when you’re ready to move to the cloud, you can use Visual Studio’s support for Entity Framework migration to move your database, or merge changes with a remote data store. See Migrations overview.
On the Connected Services tab, you can find the migration commands by clicking on the three dots, as shown in the screenshot:

Commands are available there to create new migrations, apply them directly, or generate SQL scripts that apply the migrations.
Add migration
When a data model change is introduced, you can use Entity Framework Core tools to add a corresponding migration that describes in code the updates necessary to keep the database schema in sync. Entity Framework Core compares the current model against a snapshot of the old model to determine the differences, and generates migration source files. The files are added to your project, usually in a folder called Migrations and can be tracked in your project’s source control like any other source file.
When you choose this option, you’re asked to provide the context class name that represents the database schema you want to migrate.

Update database
After a migration has been created, it can be applied to a database. Entity Framework updates your database and your schema with the changes specified in the migration code. When you choose this option, you’re asked to provide the context class name that represents the database schema you want to migrate.
Generate SQL script
The recommended way to deploy migrations to a production database is by generating SQL scripts. The advantages of this strategy include the following:
- SQL scripts can be reviewed for accuracy; this is important since applying schema changes to production databases is a potentially dangerous operation that could involve data loss.
- In some cases, the scripts can be tuned to fit the specific needs of a production database.
- SQL scripts can be used in conjunction with a deployment technology, and can even be generated as part of your CI process.
- SQL scripts can be provided to a DBA, and can be managed and archived separately.
When you use this option, you’re asked the database context class and the location for the script file.

Open in SQL Server Object Explorer
For convenience, this command lets you jump to the SQL Server Object Explorer, so you can view tables and other database entities, and work directly with your data. See Object explorer.

Next steps
You can continue with the quickstarts for Azure SQL database, but instead of starting from the beginning, you can start after the initial connection is set up. If you’re using Entity Framework, you can start at Add the code to connect to Azure SQL Database. If you’re using SqlClient or ADO.NET data classes, you can start at Add the code to connect to Azure SQL Database.
Your code won’t exactly match what is used in the quickstarts, which use a different way of getting the connection string. The connection strings are secrets and are securely stored as explained in Safe storage of app secrets in development in ASP.NET Core. In particular, to read the connection string from the secrets store, you can add code as in Read the secret via the configuration API. In ASP.NET Core projects, the connection string created by Connected Services is available in a configuration object. You can access it by a property on the WebApplicationBuilder class ( builder in many project templates), as in the following example:
var connection = builder.Configuration["ConnectionStrings:ConnectionString1"];
See also
- Azure SQL Database product page
- Azure SQL Database documentation
- Connected services (Visual Studio for Mac)
SQL Prompt

Did you know Redgate has more extensions for Visual Studio to help you extend DevOps processes to SQL Server databases? Check out:
- SQL Change Automation – develop, source control, and safely automate deployments of database changes alongside application changes.
- SQL Search – speed up database development by quickly searching for SQL objects and exploring across SQL Server databases.
Краткое руководство. Подключение и запрос данных с помощью Visual Studio Code
Visual Studio Code — это графический редактор кода для Linux, macOS и Windows. Он поддерживает расширения, включая расширение mssql для запроса SQL Server, База данных SQL Azure, Управляемый экземпляр SQL Azure и базы данных в Azure Synapse Analytics. В этом кратком руководстве вы используете Visual Studio Code для подключения к База данных SQL Azure или Управляемый экземпляр SQL Azure, а затем выполните инструкции Transact-SQL для запроса, вставки, обновления и удаления данных.
Необходимые компоненты
Важно! Скрипты в этой статье предназначены для использования базы данных Adventure Works. Используя Управляемый экземпляр SQL, необходимо импортировать базу данных Adventure Works в базу данных экземпляра или изменить скрипты в этой статье для использования базы данных Wide World Importers.
Установка Visual Studio Code
Убедитесь, что вы установили последнюю версию Visual Studio Code. Инструкции по установке см. в разделе «Установка Visual Studio Code».
Настройка Visual Studio Code
Windows
Загрузите расширение mssql, выполнив следующие действия.
- Откройте Visual Studio Code.
- Откройте область расширений (или CTRL+SHIFT+X).
- sql Найдите и установите расширение SQL Server (mssql).
Дополнительные инструкции по установке см. в mssql для Visual Studio Code.
macOS
Для macOS необходимо установить OpenSSL. Это предварительное требование для платформы .NET Core, используемой для расширения mssql. Откройте терминал и введите следующие команды для установки brew и OpenSSL.
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" brew update brew install openssl mkdir -p /usr/local/lib ln -s /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib /usr/local/lib/ ln -s /usr/local/opt/openssl/lib/libssl.1.0.0.dylib /usr/local/lib/
Linux (Ubuntu)
Загрузите расширение mssql, выполнив следующие действия.
- Откройте Visual Studio Code.
- Откройте область расширений (или CTRL+SHIFT+X).
- sql Найдите и установите расширение SQL Server (mssql).
Дополнительные инструкции по установке см. в mssql для Visual Studio Code.
Получение сведений о подключении к серверу
Получите сведения, необходимые для подключения к Базе данных SQL Azure. Вам потребуется полное имя сервера или имя узла, имя базы данных и сведения о входе для предстоящих процедур.
- Войдите на портал Azure.
- Перейдите на страницу Базы данных SQL или Управляемые экземпляры SQL.
- На странице Обзор просмотрите полное имя сервера рядом с полем Имя сервера для Базы данных SQL или полное имя сервера рядом с полем Узел для Управляемого экземпляра SQL. Чтобы скопировать имя сервера или имя узла, наведите на него указатель мыши и щелкните значок копирования.
Выбор режима языка SQL
В Visual Studio Code укажите для режима языка значение SQL, чтобы активировать команды mssql и T-SQL IntelliSense.
- Откройте новое окно Visual Studio Code.
- Нажмите клавиши CTRL+N. Откроется новый обычный текстовый файл.
- В правом нижнем углу строки состояния выберите Обычный текст.
- В раскрывающемся списке «Выбор языкового режима «, который открывается, выберите SQL.
Подключение к базе данных
Установите подключение к серверу с помощью Visual Studio Code.
Прежде чем продолжить, убедитесь, что у вас есть сервер и информация о входе. Если при вводе данных профиля подключения переключиться с Visual Studio Code, понадобится начать создание профиля заново.
- В Visual Studio Code нажмите клавиши CTRL+SHIFT+P (или F1), чтобы открыть палитру команд.
- Введите connect и выберите MS SQL:Подключение.
- Выберите и создайте профиль Подключение ion.
- Следуйте инструкциям на экране, чтобы указать свойства для нового профиля подключения. После указания каждого значения нажимайте клавишу ВВОД, чтобы продолжить.
Свойство Предлагаемое значение Описание Имя сервера Полное имя сервера Примерно такое: mynewserver20170313.database.windows.net. Имя базы данных mySampleDatabase База данных для подключения. Проверка подлинности имя для входа SQL В этом руководстве используется проверка подлинности SQL. Имя пользователя User name Имя пользователя учетной записи администратора сервера, используемое для создания сервера. Пароль (имя входа SQL) Password Пароль учетной записи администратора сервера, используемый для создания сервера. Сохранить пароль? «Да» или «Нет» Чтобы не вводить пароль каждый раз, выберите Да. Введите имя для этого профиля Имя профиля, например mySampleProfile Сохраненный профиль повышает скорость подключения при последующих входах. В случае успешного выполнения появится уведомление о том, что профиль создан и подключен.
Запрос данных
Выполните указанную нижу инструкцию Transact-SQL SELECT, чтобы запросить 20 основных продуктов из категории.
-
В окне редактора вставьте следующий запрос SQL.
SELECT pc.Name AS CategoryName, p.name AS ProductName FROM [SalesLT].[ProductCategory] pc INNER JOIN [SalesLT].[Product] p ON pc.ProductCategoryId = p.ProductCategoryId;

Вставка данных
Выполните указанную ниже инструкцию Transact-SQL INSERT, чтобы добавить новый продукт в таблицу SalesLT.Product .
-
Замените предыдущий запрос следующим содержимым.
INSERT INTO [SalesLT].[Product] ( [Name], [ProductNumber], [Color], [ProductCategoryID], [StandardCost], [ListPrice], [SellStartDate] ) VALUES ( 'myNewProduct', 123456789, 'NewColor', 1, 100, 100, GETDATE() );
Обновление данных
Выполните указанную ниже инструкцию Transact-SQL UPDATE, чтобы обновить добавленный продукт.
-
Замените предыдущий запрос следующим содержимым:
UPDATE [SalesLT].[Product] SET [ListPrice] = 125 WHERE Name = 'myNewProduct';
Удаление данных
Выполните указанную ниже инструкцию Transact-SQL DELETE, чтобы удалить новый продукт.
-
Замените предыдущий запрос следующим содержимым:
DELETE FROM [SalesLT].[Product] WHERE Name = 'myNewProduct';
Следующие шаги
- Краткое руководство. Использование SQL Server Management Studio для подключения к базе данных в База данных SQL Azure и запроса данных
- Использование редактора SQL Query в портал Azure для подключения и запроса данных
- Создание интегрированной среды разработки базы данных с записью блога расширения MSSQL
Transact-SQL in Visual Studio Code
Turn Visual Studio Code into a powerful editor for Transact-SQL (T-SQL) development, with the mssql extension available in the VS Code Marketplace. The mssql extension is optimized to work with SQL Server running on-premises, in any cloud, Azure SQL Database, and Azure SQL Data Warehouse.
Connect to SQL databases, type T-SQL code, execute T-SQL code, view results, and save results as JSON or CSV files. While typing T-SQL code, you get rich T-SQL language features like T-SQL IntelliSense (code completion), syntax highlighting, linting, code navigation and code snippets.
Download VS Code — If you haven’t downloaded VS Code yet, quickly install for your platform (Linux, macOS or Windows).
Install T-SQL support
Add T-SQL language support to VS Code by installing the mssql extension from the VS Code marketplace as follows:
- Open the Extensions view from VS Code Side Bar ( ⇧⌘X (Windows, Linux Ctrl+Shift+X ) ).
- Type «mssql» in the search bar, click Install, and reload VS Code when prompted.

Connect and Execute T-SQL
Easily connect to SQL Server running on-premises, in any cloud, Azure SQL Database, and Azure SQL Data Warehouse. Then, execute your T-SQL statements and batches to view results and messages — all within VS Code. Your recent connections are saved across sessions, so you can quickly connect to your databases again.
View and Save Results
View results and messages when you execute your T-SQL code. Save results as a JSON or CSV file to use the data in your applications with just a few clicks.
T-SQL IntelliSense
As you type T-SQL code in the editor, VS Code provides intelligent code completion for T-SQL keywords, suggestions for schema object names (tables, columns, views), and parameter help for functions and procedures when connected to a database.
Linting
Linting is the analysis of your T-SQL code for potential syntax errors. Use Visual Studio Code to quickly navigate to the errors and warnings in your T-SQL code as you type.
Peek Definition/Go to Definition
Use Peek Definition or Go to Definition to quickly browse the definition of schema objects in your database such as tables, functions, and procedures while typing T-SQL code.
Snippets
T-SQL snippets provide code templates for commonly used T-SQL statements. Type «sql» to get the list of T-SQL snippets.
Next steps
- Download the free SQL Server 2017 Developer Edition.
- Install the mssql extension from the Visual Studio Code Marketplace.
- Build an app using SQL Server — Get started with SQL Server on macOS, Linux, and Windows using your favorite programming language.
- Contribute to the mssql extension on GitHub. Submit a bug report or a feature suggestion on our GitHub Issue Tracker.
Further Reading
- SQL Server documentation
- SQL Server on Linux documentation
- SQL Server Blog
