How to connect to sql server

How to connect to sql server

Connecting to an Instance of SQL Server

The first programming step in a SQL Server Management Objects (SMO) application is to create an instance of the Server object and to establish its connection to an instance of Microsoft SQL Server.

You can create an instance of the Server object and establish a connection to the instance of SQL Server in three ways. The first is using a ServerConnection object variable to provide the connection information. The second is to provide the connection information by explicitly setting the Server object properties. The third is to pass the name of the SQL Server instance in the Server object constructor.

Using a ServerConnection object

The advantage of using the ServerConnection object variable is that the connection information can be reused. Declare a Server object variable. Then, declare a ServerConnection object and set properties with connection information such as the name of the instance of SQL Server, and the authentication mode. Then, pass the ServerConnection object variable as a parameter to the Server object constructor. It is not recommended to share connections between different server objects at the same time. Use the Copy method to get a copy of the existing connection settings.

Setting Server object properties explicitly

Alternatively, you can declare the Server object variable and call the default constructor. As is, the Server object tries to connect to the default instance of SQL Server with all the default connection settings.

Providing the SQL Server instance name in the Server object constructor

Declare the Server object variable and pass the SQL Server instance name as a string parameter in the constructor. The Server object establishes a connection with the instance of SQL Server with the default connection settings.

Connection Pooling

It is typically not required to call the Connect method of the ServerConnection object. SMO will automatically establish a connection when required, and release the connection to the connection pool after it has finished performing operations. When the Connect method is called, the connection is not released to the pool. An explicit call to the Disconnect method is required to release the connection to the pool. Additionally, you can request a non-pooled connection by setting the NonPooledConnection property of the ServerConnection object.

Multithreaded Applications

For multithreaded applications, a separate ServerConnection object should be used in each thread.

Connecting to an Instance of SQL Server for RMO

Replication Management Objects (RMO) uses a slightly different method from SMO to connect to a replication server.

RMO programming objects require that a connection to an instance of SQL Server is made by using the ServerConnection object implemented by the Microsoft.SqlServer.Management.Common namespace. This connection to the server is made independently of an RMO programming object. It is then it is passed to the RMO object either during instance creation or by assignment to the ConnectionContext property of the object. In this manner, an RMO programming object and the connection object instances can be created and managed separately, and a single connection object can be reused with multiple RMO programming objects. The following rules apply for connections to a replication server:

All properties for the connection are defined for a specified ServerConnection object.

Each connection to an instance of SQL Server must have its own ServerConnection object.

All authentication information to make the connection and successfully log on to the server is supplied in the ServerConnection object.

By default, connections are made by using Microsoft Windows Authentication. To use SQL Server Authentication, LoginSecure must be set to False and Login and Password must be set to a valid SQL Server logon and password. Security credentials must always be stored and handled securely, and supplied at run time whenever possible.

The Connect method must be called before passing the connection to any RMO programming object.

Examples

Connecting to the Local Instance of SQL Server by Using Windows Authentication in Visual Basic

Connecting to the local instance of SQL Server does not require much code. Instead, it relies on default settings for authentication method and server. The first operation that requires data to be retrieved will cause a connection to be created.

Connecting to the Local Instance of SQL Server by Using Windows Authentication in Visual C#

Connecting to the local instance of SQL Server does not require much code. Instead, it relies on default settings for authentication method and server. The first operation that requires data to be retrieved will cause a connection to be created.

Connecting to a Remote Instance of SQL Server by Using Windows Authentication in Visual Basic

When you connect to an instance of SQL Server by using Windows Authentication, you do not have to specify the authentication type. Windows Authentication is the default.

Connecting to a Remote Instance of SQL Server by Using Windows Authentication in Visual C#

When you connect to an instance of SQL Server by using Windows Authentication, you do not have to specify the authentication type. Windows Authentication is the default.

Connecting to an Instance of SQL Server by Using SQL Server Authentication in Visual Basic

When you connect to an instance of SQL Server by using SQL Server Authentication, you must specify the authentication type. This example demonstrates the alternative method of declaring a ServerConnection object variable, which enables the connection information to be reused.

Connecting to an Instance of SQL Server by Using SQL Server Authentication in Visual C#

When you connect to an instance of SQL Server by using SQL Server Authentication, you must specify the authentication type. This example demonstrates the alternative method of declaring a ServerConnection object variable, which enables the connection information to be reused.

Урок 1. Подключение к ядру СУБД

При установке ядра СУБД SQL Server установленные средства зависят от выпуска и выбора настроек. На этом уроке рассматриваются важнейшие средства, а также показываются способы подключения и выполнения одной из базовых функций (разрешение входа дополнительным пользователям).

Это занятие содержит следующие задачи.

Средства для начала работы

Основные средства

SQL Server Management Studio (SSMS) — это основной инструмент для администрирования ядра СУБД и написания кода Transact-SQL. Он размещается в оболочке Visual Studio. Решение SSMS доступно бесплатно для скачивания. Последнюю версию можно использовать с более старыми версиями ядра СУБД.

Диспетчер конфигурации SQL Server устанавливается как с SQL Server, так и с клиентскими средствами. Он позволяет включать серверные протоколы, настраивать параметры протокола, например порты TCP, настраивать автоматический запуск служб сервера и настраивать соединение клиентских компьютеров. Это средство может настроить дополнительные элементы подключения, но не активирует компоненты.

Пример базы данных

Примеры баз данных и примеров не включены в SQL Server. Большинство примеров, описанных в электронной документации по SQL Server, используют примеры баз данных AdventureWorks.

Начало работы в среде SQL Server Management Studio
Запуск диспетчера конфигурации SQL Server

Соединение с помощью среды Management Studio

В этом разделе рассматривается подключение к локальному экземпляру SQL Server. Чтобы подключиться к Базе данных SQL Azure, см. краткое руководство Использование SSMS для подключения к Базе данных SQL Azure или Управляемому экземпляру SQL Azure.

Определение имени экземпляра компонента Database Engine
Подтверждение того, что компонент ядра СУБД запущен

В зарегистрированных серверах, если имя экземпляра SQL Server имеет зеленую точку со белой стрелкой рядом с именем, ядро СУБД выполняется и никаких дальнейших действий не требуется.

Если имя экземпляра SQL Server имеет красную точку с белым квадратом рядом с именем, ядро СУБД останавливается. Щелкните правой кнопкой мыши имя ядра СУБД, выберите «Управление службой» и выберите «Пуск«. После диалогового окна подтверждения ядро СУБД должно запускаться, а круг должен выглядеть зеленым с белой стрелкой.

Подключение к компоненту ядра СУБД

При установке SQL Server была выбрана по крайней мере одна учетная запись администратора. Выполнив вход в Windows с правами администратора, выполните указанные ниже действия.

How to connect to sql server. Смотреть фото How to connect to sql server. Смотреть картинку How to connect to sql server. Картинка про How to connect to sql server. Фото How to connect to sql server

How to connect to sql server. Смотреть фото How to connect to sql server. Смотреть картинку How to connect to sql server. Картинка про How to connect to sql server. Фото How to connect to sql server

В этом учебнике предполагается, что вы не знакомы с SQL Server и у вас нет проблем с подключением. Этого достаточно в большинстве случаев, и это позволяет упростить учебник. Подробные инструкции по устранению неполадок см. в разделе Устранение неполадок при соединении с компонентом SQL Server Database Engine.

Авторизация дополнительных подключений

Теперь, когда вы подключились к SQL Server от имени администратора, одной из первых задач является авторизация других пользователей для подключения. Это делается посредством создания имени входа и предоставления ему разрешения на доступ к базе данных в качестве пользователя. Имена входа могут быть или именами входа для проверки подлинности Windows, использующей учетные данные Windows, или именами входа для проверки подлинности SQL Server, при которой учетные данные хранятся в SQL Server и не зависят от учетных данных Windows. Дополнительные варианты входа включают вход Azure Active Directory, дополнительные сведения о котором приведены в статье Использование аутентификации Azure Active Directory.

По возможности используйте проверку подлинности Windows.

Создание имени входа для проверки подлинности Windows

На странице Общие в поле Имя входа введите имя входа Windows в следующем формате: \

How to connect to sql server. Смотреть фото How to connect to sql server. Смотреть картинку How to connect to sql server. Картинка про How to connect to sql server. Фото How to connect to sql server

Это базовые сведения, позволяющие начать работу. SQL Server предоставляет расширенную среду безопасности, а безопасность, очевидно, является важным аспектом операций с базами данных.

Краткое руководство. Подключение к экземпляру SQL Server и выполнение запросов с помощью SQL Server Management Studio (SSMS)

Начало работы с SQL Server Management Studio (SSMS) для подключения к экземпляру базы данных SQL Server и выполнения некоторых команд Transact-SQL (T-SQL).

В статье показано, как выполнять следующие задачи:

В этой статье описывается подключение к экземпляру SQL Server и выполнение запросов к нему. Для сведений об Azure SQL см. статью о подключении к Базе данных Azure SQL и Управляемому экземпляру SQL и выполнении запросов к ним.

Чтобы использовать Azure Data Studio см. статьи о выполнении подключения и запросов к SQL Server, Базе данных SQL Azure и Azure Synapse Analytics.

Дополнительные сведения о SQL Server Management Studio см. в статье с дополнительными советами и рекомендациями.

Предварительные требования

Для работы с данным руководством необходимо следующее:

Подключение к экземпляру SQL Server

Чтобы подключиться к экземпляру SQL Server, выполните следующие действия:

Запустите среду SQL Server Management Studio. При первом запуске SSMS откроется окно Подключение к серверу. Если этого не происходит, вы можете открыть его вручную, последовательно выбрав Обозреватель объектов > Подключить > Ядро СУБД.

How to connect to sql server. Смотреть фото How to connect to sql server. Смотреть картинку How to connect to sql server. Картинка про How to connect to sql server. Фото How to connect to sql server

ПараметрРекомендуемые значенияОписание
Тип сервераЯдро СУБДВ поле Тип сервера выберите Ядро СУБД (обычно это параметр по умолчанию).
Имя сервераПолное имя сервераВ поле Имя сервера введите имя SQL Server (при локальном подключении в качестве имени сервера также можно использовать localhost). Если вы НЕ ИСПОЛЬЗУЕТЕ экземпляр по умолчанию — MSSQLSERVER — необходимо ввести имя сервера и имя экземпляра.

Если вы не знаете, как определить имя экземпляра SQL Server, см. раздел Дополнительные советы и рекомендации по использованию SSMS.

АутентификацияПроверка подлинности Windows

Проверка подлинности SQL Server

По умолчанию используется проверка подлинности Windows.

Также для подключения можно использовать режим Проверка подлинности SQL Server. Если выбран режим Проверка подлинности SQL Server, необходимо ввести имя пользователя и пароль.

Дополнительные сведения о типах проверки подлинности см. в разделе Подключение к серверу (ядро СУБД).

Имя входаИдентификатор пользователя учетной записи сервераИдентификатор пользователя учетной записи сервера, используемой для входа на сервер. Имя для входа, используемое для проверки подлинности SQL Server.
ПарольПароль учетной записи сервераПароль учетной записи сервера, используемой для входа на сервер. Пароль, используемый для проверки подлинности SQL Server.

How to connect to sql server. Смотреть фото How to connect to sql server. Смотреть картинку How to connect to sql server. Картинка про How to connect to sql server. Фото How to connect to sql server

После заполнения всех полей выберите Подключить.

Вы также можете изменить дополнительные параметры подключения, выбрав Параметры. Примеры параметров подключения: база данных, к которой вы подключаетесь, время ожидания подключения и сетевой протокол. В этой статье во всех полях указываются значения по умолчанию.

Чтобы убедиться в успешном подключении к экземпляру SQL Server, разверните и изучите объекты в обозревателе объектов, для которых отображаются имя сервера, версия SQL Server и имя пользователя. Эти объекты могут различаться в зависимости от типа сервера.

How to connect to sql server. Смотреть фото How to connect to sql server. Смотреть картинку How to connect to sql server. Картинка про How to connect to sql server. Фото How to connect to sql server

Создание базы данных

Выполните следующие действия, чтобы создать базу данных с именем TutorialDB:

Щелкните правой кнопкой мыши экземпляр сервера в обозревателе объектов и выберите Создать запрос.

How to connect to sql server. Смотреть фото How to connect to sql server. Смотреть картинку How to connect to sql server. Картинка про How to connect to sql server. Фото How to connect to sql server

Вставьте в окно запроса следующий фрагмент кода T-SQL:

Чтобы запустить запрос, нажмите кнопку Выполнить (или клавишу F5).

How to connect to sql server. Смотреть фото How to connect to sql server. Смотреть картинку How to connect to sql server. Картинка про How to connect to sql server. Фото How to connect to sql server

После выполнения запроса в списке баз данных в обозревателе объектов появится новая база данных TutorialDB. Если она не отображается, щелкните правой кнопкой мыши узел Базы данных и выберите Обновить.

Создание таблицы

В этом разделе вы создадите таблицу в новой базе данных TutorialDB. Так как редактор запросов все еще находится в контексте базы данных master, переключите контекст подключения на базу TutorialDB, сделав следующее.

Выберите нужную базу данных в раскрывающемся списке, как показано здесь:

How to connect to sql server. Смотреть фото How to connect to sql server. Смотреть картинку How to connect to sql server. Картинка про How to connect to sql server. Фото How to connect to sql server

Вставьте в окно запроса следующий фрагмент кода T-SQL:

Чтобы запустить запрос, нажмите кнопку Выполнить (или клавишу F5).

После выполнения запроса в списке таблиц в обозревателе объектов появится новая таблица Customers. Если таблица не отображается, щелкните правой кнопкой мыши узел TutorialDB > Таблицы в обозревателе объектов, а затем выберите Обновить.

How to connect to sql server. Смотреть фото How to connect to sql server. Смотреть картинку How to connect to sql server. Картинка про How to connect to sql server. Фото How to connect to sql server

Вставка строк

Вставьте в созданную таблицу Customers какие-нибудь строки. Вставьте следующий фрагмент кода T-SQL в окно запросов и нажмите кнопку Выполнить.

Запрос к таблице и просмотр результатов

Результаты запроса выводятся под текстовым окном запроса. Чтобы запросить таблицу Customers и просмотреть вставленные строки, выполните следующие действия:

Вставьте следующий фрагмент кода T-SQL в окно запросов и нажмите кнопку Выполнить.

Результаты запроса отображаются под областью, где был введен текст.

How to connect to sql server. Смотреть фото How to connect to sql server. Смотреть картинку How to connect to sql server. Картинка про How to connect to sql server. Фото How to connect to sql server

Вы также можете изменить представление результатов одним из следующих способов:

How to connect to sql server. Смотреть фото How to connect to sql server. Смотреть картинку How to connect to sql server. Картинка про How to connect to sql server. Фото How to connect to sql server

Проверка свойств подключения с помощью таблицы окна запросов

Сведения о свойствах подключения приводятся под результатами запроса. После выполнения запроса из предыдущего этапа просмотрите свойства подключения в нижней части окна запросов.

Вы можете определить, к какому серверу и какой базе данных вы подключены и под каким именем пользователя выполнен вход.

Кроме того, вы можете проверить длительность запроса и число строк, возвращенных предыдущим запросом.

How to connect to sql server. Смотреть фото How to connect to sql server. Смотреть картинку How to connect to sql server. Картинка про How to connect to sql server. Фото How to connect to sql server

Устранение проблем подключения

Сведения о способах устранения неполадок с подключением к экземпляру ядра СУБД SQL Server на отдельном сервере см. в статье Устранение неполадок при соединении с ядром СУБД SQL Server.

Дальнейшие действия

Лучший способ познакомиться с SSMS — это поработать в среде самостоятельно. Эти статьи помогут вам ознакомиться с различными функциями SSMS.

Lesson 1: Connecting to the Database Engine

When you install the SQL Server Database Engine, the tools that are installed depend upon the edition and your setup choices. This lesson reviews the principal tools, and shows you how to connect and perform a basic function (authorizing more users).

This lesson contains the following tasks:

Tools for getting started

Basic tools

SQL Server Management Studio (SSMS) is the principal tool for administering the Database Engine and writing Transact-SQL code. It’s hosted in the Visual Studio shell. SSMS is available as a free download. The latest version can be used with older versions of the Database Engine.

SQL Server Configuration Manager installs with both SQL Server and the client tools. It lets you enable server protocols, configure protocol options such as TCP ports, configure server services to start automatically, and configure client computers to connect in your preferred manner. This tool configures the more advanced connectivity elements but doesn’t enable features.

Sample database

The sample databases and samples aren’t included with SQL Server. Most of the examples that are described in SQL Server Books Online use the AdventureWorks sample databases.

To start SQL Server Management Studio
To start SQL Server Configuration Manager

Connecting with Management Studio

This topic discusses connecting to an on-premises SQL Server. To connect to Azure SQL Database, see Quickstart: Use SSMS to connect to and query Azure SQL Database or Azure SQL Managed Instance.

To determine the name of the instance of the Database Engine
To verify that the Database Engine is running

In Registered Servers, if the name of your instance of SQL Server has a green dot with a white arrow next to the name, the Database Engine is running and no further action is necessary.

If the name of your instance of SQL Server has a red dot with a white square next to the name, the Database Engine is stopped. Right-click the name of the Database Engine, select Service Control, and then select Start. After a confirmation dialog box, the Database Engine should start and the circle should turn green with a white arrow.

To connect to the Database Engine

At least one administrator account was selected when SQL Server was being installed. Perform the following step while logged into Windows as an administrator.

How to connect to sql server. Смотреть фото How to connect to sql server. Смотреть картинку How to connect to sql server. Картинка про How to connect to sql server. Фото How to connect to sql server

How to connect to sql server. Смотреть фото How to connect to sql server. Смотреть картинку How to connect to sql server. Картинка про How to connect to sql server. Фото How to connect to sql server

This tutorial assumes you are new to SQL Server and have no special problems connecting. This should be sufficient for most people and this keeps this tutorial simple. For detailed troubleshooting steps, see Troubleshooting Connecting to the SQL Server Database Engine.

Authorizing extra connections

Now that you’ve connected to SQL Server as an administrator, one of your first tasks is to authorize other users to connect. You do this by creating a login and authorizing that login to access a database as a user. Logins can be either Windows Authentication logins, which use credentials from Windows, or SQL Server Authentication logins, which store the authentication information in SQL Server and are independent of your Windows credentials. Extra login options include Azure Active Directory logins, which you can find out more information by following the article, Use Azure Active Directory authentication.

Use Windows Authentication whenever possible.

Create a Windows Authentication login

On the General page, in the Login name box, type a Windows login in the format: \

How to connect to sql server. Смотреть фото How to connect to sql server. Смотреть картинку How to connect to sql server. Картинка про How to connect to sql server. Фото How to connect to sql server

This is basic information to get you started. SQL Server provides a rich security environment, and security is obviously an important aspect of database operations.

Connect to Server (Database Engine)

Many factors can affect your ability to connect to SQL Server. For help, see the following resources:

Options

Server type
When registering a server from Object Explorer, select the type of server to connect to: Database Engine, Analysis Services, Reporting Services, or Integration Services. The rest of the dialog shows only the options that apply to the selected server type. When registering a server from Registered Servers, the Server type box is read-only, and matches the type of server displayed in the Registered Servers component. To register a different type of server, select Database Engine, Analysis Services, Reporting Services, SQL Server Compact, or Integration Services from the Registered Servers toolbar before starting to register a new server.

Server name
Select the server instance to connect to. The server instance last connected to is displayed by default.

Connections are typically persisted in the «Most Recently Used» (MRU) history. To remove entries from the MRU, simply click on the Server name combobox, select the name of the server to remove, then press the DEL key.

Authentication
The current version of SSMS, offers five authentication modes when connecting to an instance of the Database Engine. If your Authentication dialog box does not match the following list, download the most recent version of SSMS, from Download SQL Server Management Studio (SSMS).

Windows Authentication
Microsoft Windows Authentication mode allows a user to connect through a Windows user account.

Login
Enter the login to connect with. This option is only available if you have selected to connect using SQL Server Authentication or Active Directory Password Authentication.

Connections are typically persisted in the «Most Recently Used» (MRU) history. To remove entries from the MRU, simply click on the Server name combobox, select the name of the server to remove, then press the DEL key. This was introduced with SSMS 18.5.

Connect
Click to connect to the server.

Options
Click to display the Connection Properties, and Additional Connection Parameters tabs.

Источники информации:

Добавить комментарий

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