Ошибка подключения к базе sql


Abstract

This topic was updated and moved into SQL Server Books Online in June. 2016. See
https://msdn.microsoft.com/library/mt750266.aspx 

Original topic follows:

This is an exhaustive list of troubleshooting techniques to use when you cannot connect to the SQL Server Database Engine. These steps are not in the order of the most likely problems which you probably already tried. These steps
are in order of the most basic problems to more complex problems. These steps assume that you are connecting to SQL Server from another computer by using the TCP/IP protocol, which is the most common situation. These steps are written for SQL Server 2008 R2
with a client running Windows 7, however the steps generally apply to other versions of SQL Server and other operating systems with only slight modifications.

These instructions are particularly useful when troubleshooting the «Connect to Server» error, which can be Error Number: 11001 (or 53), Severity: 20, State: 0

  • «A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.
    »
  • «(provider: Named Pipes Provider, error: 40 — Could not open a connection to SQL Server) (Microsoft SQL Server, Error: 53)» or «(provider: TCP Provider, error: 0 — No such host is known.) (Microsoft SQL Server, Error: 11001)»

This error usually means that the SQL Server computer can’t be found or that the TCP port number is either not known, or is not the correct port number, or is blocked by a firewall.

Not included

  • This topic does not include information about SSPI errors. For SSPI errors, see How to troubleshoot the «Cannot generate SSPI context» error message
  • This topic does not include information about Kerberos errors. For help, see Microsoft Kerberos Configuration Manager for SQL Server.
  • This topic does not include information about SQL Azure Connectivity.

Table of Contents

  • Abstract
    • Not included
  • Gathering Information about the Instance of SQL Server
  • Enable Protocols
  • Testing TCP/IP Connectivity
  • Testing a Local Connection
  • Opening a Port in the Firewall
  • Testing the Connection
  • See Also

Gathering Information about the Instance of SQL Server

  1. Confirm the instance of the SQL Server Database Engine is installed and running.

    1. Logon to the computer hosting the instance of SQL Server.
    2. On the Start menu, point to All Programs, point to Microsoft SQL Server 2008 R2, point to Configuration Tools, and then click SQL Server Configuration Manager.
    3. Using Configuration Manager, in the left pane select SQL Server Services. In the right-pane confirm that the instance of the Database Engine is present and running. The instance named MSSQLSERVER is
      a default (unnamed) instance. There can only be one default instance. Other (named) instances will have their names listed between the parentheses. SQL Server Express uses the name SQLEXPRESS as the instance name unless someone named it something
      else during setup. Make a note of the name of the instance that you are trying to connect to. Also, confirm that the instance is running, by looking for the green arrow. If the instance has a red square, right-click the instance and then click Start.
      It should turn green.        
    4. If you are attempting to connect to a named instance, make sure the SQL Server Browser service is running.
  2. Get the IP Address of the computer.
    1. On the Start menu, click Run. In the Run window type cmd, and then click OK.
    2. In the command prompt window, type ipconfig and then press enter. Make a note of the IPv4 Address and the IPv6 Address. (SQL Server can connect using the older IP version 4 protocol
      or the newer IP version 6 protocol. Your network could allow either or both. Most people start by troubleshooting theIPv4 address. It’s shorter and easier to type.)
  3. Get the TCP port number used by SQL Server. In most cases you are connecting to the Database Engine from another computer using the TCP protocol.
    1. Using SQL Server Management Studio on the computer running SQL Server, connect to the instance of SQL Server. In Object Explorer, expand Management, expand SQL Server Logs, and then double-click
      the current log.
    2. In the Log Viewer, click the Filter button on the toolbar. In the Message contains text box, type server is listening on, click Apply filter, and then click OK.
    3. A message similar to Server is listening on [ ‘any’ <ipv4> 1433] should be listed. This message indicates that this instance of SQL Server is listening on all the computers IP Addresses (for IP version 4) and
      is listening to TCP port 1433. (TCP port 1433 is usually the port used by the Database Engine. Only one instance of SQL Server can use a port, so if there is more than one instance of SQL Server installed, some instances must use other port numbers.)

Note: IP address 127.0.0.1 is probably listed. It is called the loopback adapter address and can only be connected to from processes on the same computer. It can be useful for troubleshooting, but you can’t use it to connect from another
computer.


Enable Protocols

In many installations of SQL Server, connecting to the Database Engine from another computer is not enabled unless an administrator uses Configuration Manager to enable it. To enable connections from another computer:

  1. On the Start menu, point to All Programs, point to Microsoft SQL Server 2008 R2, point to Configuration Tools, and then click SQL Server Configuration Manager.
  2. Using Configuration Manager, in the left pane expand SQL Server Network Configuration (or SQL Server Network Configuration (32bit)), and then select the instance of SQL Server that you want to
    connect to. The right-pane lists the connection protocols available. Shared Memory is normally enabled. It can only be used from the same computer, so most installations leave Shared Memory enabled. To connect to SQL Server from another computer you will normally
    use TCP/IP. If TCP/IP is not enabled, right-click TCP/IP, and then click Enable.
  3. If you changed the enabled setting for any protocol you must restart the Database Engine. In the left pane select SQL Server Services. In the right-pane, right-click the instance of the Database Engine, and then
    click Restart.

Testing TCP/IP Connectivity

Connecting to SQL Server by using TCP/IP requires that Windows can establish the connection.

  1. On the Start menu, click Run. In the Run window type cmd, and then click OK.
  2. In the command prompt window, type ping and then the IP Address of the computer that is running SQL Server. For example, ping 192.168.1.101 using an IPv4 address, or ping fe80::d51d:5ab5:6f09:8f48%11 using
    an IPv6 address. (You must replace the numbers after ping with the IP addresses on your computer.)
  3. If your network is properly configured you will receive a response such as Reply from <IP address>. If you receive an error such as «Destination host unreachable.» or «Request timed out.»
    then TCP/IP is not correctly configured. (Check that the IP address was correct and was correctly typed.) Errors at this point could indicate a problem with the client computer, the server computer, or something about the network such as a router.  For more
    information, see How to Troubleshoot Basic TCP/IP Problems.
  4. Next, if the ping test succeeded using the IP address, a test that the computer name can be resolved to the TCP/IP address. On the client computer, in the command prompt window, type ping and then the computer
    name of the computer that is running SQL Server. For example, ping newofficepc.
  5. If you receive an error such as «Destination host unreachable.» or «Request timed out.» you might have old (stale) name resolution information cached on the client computer. Type ipconfig
    /flushdns
     to clear the DNS (Dynamic Name Resolution) cache. Then ping the computer by name again. With the DNS cache empty, the client computer will check for the newest information about the IP address for the server computer.
  6. If your network is properly configured you will receive a response such as Reply from <IP address>. If you can successfully ping the server computer by IP address but receive an error such as «Destination
    host unreachable.
    » or «Request timed out.» when pinging by computer name, then name resolution is not correctly configured. (For more information, see How to Troubleshoot Basic TCP/IP
    Problems.) Successful name resolution is not required to connect to SQL Server, but if the computer name cannot be resolved, then connections must be made specifying the IP address. This is not ideal, but name resolution can be fixed later.

Testing a Local Connection

Before troubleshooting a connection problem from another computer, first test your ability to connect from a client application on the computer that is running SQL Server. This procedure
uses SQL Server Management Studio. Management Studio might not have been installed when you installed the Database Engine. You can install Management Studio from the SQL Server CD by running setup and selecting the Management Tools option. If you are running
SQL Server Express, you can download the free SQL Server Management Studio Express from http://www.microsoft.com/downloads/en/details.aspx?FamilyID=08e52ac2-1d62-45f6-9a4a-4b76a8564a2b.
(If Management Studio is not available you can test the connection using the sqlcmd.exe utility which is installed with the Database Engine.)

  1. Logon to the computer where SQL Server is installed, using a login that has permission to access SQL Server. (SQL Server 2008 installation requires at least one login to be specified as a SQL Server Administrator. If you do not
    know an administrator, see Troubleshooting: Connecting to SQL Server When System Administrators Are Locked Out.)

  2.  On the Start menu, point to All Programs, point to Microsoft SQL Server 2008 R2, and then click SQL Server Management Studio.

  3. In the Connect to Server dialog box, in the Server type box, select Database Engine. In the Authentication box, select Windows Authentication.
    In the Server name box, type one of the following:

    Connecting to:

    Type:

    Example:

    Default instance

    The computer name

    ACCNT27

    Named Instance

    The computer nameinstance name

    ACCNT27PAYROLL

    Note: When connecting to a SQL Server from a client application on the same computer, the shared memory protocol is used. Shared memory is a type of local named pipe, so sometimes errors regarding pipes are encountered.

    If you receive an error at this point, you will have to resolve it before proceeding. There are many possible things that could be a problem. Your login might not be authorized to connect. Your default database might be missing.

    Note: Some error messages passed to the client intentionally do not give enough information to troubleshoot the problem. This is a security feature to avoid providing an attacker with information about SQL Server.
    To view the complete information about the error, look in the SQL Server error log. The details are provided there. If you are receiving error 18456 «Login failed for user», Books Online topic http://msdn.microsoft.com/en-us/library/cc645917.aspx contains
    additional information about error codes. And Aaron Bertrand’s blog has a very extensive list of error codes athttp://www2.sqlblog.com/blogs/aaron_bertrand/archive/2011/01/14/sql-server-v-next-denali-additional-states-for-error-18456.aspx. 

  4.  If you can connect using shared memory, test connecting using TCP. You can force a TCP connection by specifying tcp: before the name. For example:

    Connecting to:

    Type:

    Example:

    Default instance

    tcp: The computer name

    tcp:ACCNT27

    Named Instance

    tcp: The computer name/instance name

    tcp:ACCNT27PAYROLL

    If you can connect with shared memory but not TCP, then you must fix the TCP problem. The most likely issue is that TCP is not enabled. To enable TCP, See the Enable Protocols steps above.

  5.  If your goal is to connect with an account other than an administrator account, once you can connect as an administrator, try the connection again using the Windows Authentication login or the SQL Server Authentication login that
    the client application will be using.


Opening a Port in the Firewall

Beginning with Windows XP Service Pack 2, the Windows firewall is turned on and will block connections from another computer. To connect using TCP/IP from another computer, on the SQL Server computer you must configure the firewall
to allow connections to the TCP port used by the Database Engine. If you are connecting to a named instance or a port other than TCP port 1433, you must also open the UDP port 1434 for the SQL Server Browser service. For step by step instruction on opening
a port in the Windows firewall, see How to: Configure a Windows Firewall for Database Engine Access.


Testing the Connection

Once you can connect using TCP on the same computer, it’s time to try connecting from the client computer. You could theoretically use any client application, but to avoid additional complexity, install the SQL Server Management
tools on the client and make the attempt using SQL Server Management Studio.

1. On the client computer, using SQL Server Management Studio, attempt to connect using the IP Address and the TCP port number in the format IP address comma port number. For example, 192.168.1.101,1433 If this
doesn’t work, then you probably have one of the following problems:

  • Ping of the IP address doesn’t work, indicating a general TCP configuration problem. Go back to the section Testing TCP/IP Connectivity.
  • SQL Server is not listening on the TCP protocol. Go back to the section Enable Protocols.
  • SQL Server is listening on a port other than the port you specified. Go back to the section Gathering Information about the Instance of SQL Server.
  • The SQL Server TCP port is being blocked by the firewall. Go back to the section Opening a Port in the Firewall.

2. Once you can connect using the IP address and port number, attempt to connect using the IP address without a port number. For a default instance, just use the IP address. For a named instance, use the IP address and the instance
name in the format IP address backslash instance name, for example 192.168.1.101PAYROLL If this doesn’t work, then you probably have one of the following problems:

  • If you are connecting to the default instance, it might be listening on a port other than TCP port 1433, and the client isn’t attempting to connect to the correct port number.  
  • If you are connecting to a named instance, the port number is not being returned to the client. 

Both of these problems are related to the SQL Server Browser service, which provides the port number to the client. The solutions are:

  • Start the SQL Server Browser service. Go back to the section Gathering Information about the Instance of SQL Server, section 1.b.
  • The SQL Server Browser service is being blocked by the firewall. Open UDP port 1434 in the firewall. Go back to the section Opening a Port in the Firewall.
  • The UDP port 1434 information is being blocked by a router. UDP communication (datagrams) are not designed to pass through routers. This keeps the network from getting filled with low priority traffic. You might be able to configure your router to forward
    UDP traffic, or you can decide to always provide the port number when you connect.
  • If the client computer is using Window 7 or Windows Server 2008, (or a more recent operating system,) the UDP traffic might be dropped by the client operating system because the response from the server is returned from a different IP address than was queried.
    This is a security feature blocking «loose source mapping.» For more information, see the Multiple Server IP Addresses section of the Books Online topic Troubleshooting: Timeout
    Expired. You might be able to configure the client to use the correct IP address, or you can decide to always provide the port number when you connect.

3. Once you can connect using the IP address  (or IP address and instance name), attempt to connect using the computer name (or computer name and instance name). Put tcp: in front of the computer name to force
a TCP/IP connection. For example, for a default instance use something like tcp:ACCNT27 For a named instance usesomething like tcp:ACCNT27PAYROLL If you could connect using the IP address but not using the computer name,
then you have a name resolution problem. Go back to the section Testing TCP/IP Connectivity, section 4.

4. Once you can connect using the computer name forcing TCP, attempt connecting using the computer name but not forcing TCP. For example, for a default instance use just the computer name such as ACCNT27 For a
named instance use the computer name and instance name like ACCNT27PAYROLL If you could connect using whileforcing TCP, but not without forcing TCP, then the client is probably using another protocol (such as named pipes).

a. On the client computer, using SQL Server Configuration Manager, in the left-pane expand SQL Native Client 10.0 Configuration, and then select Client Protocols.

b. On the right-pane, Make sure TCP/IP is enabled. If TCP/IP is disabled, right-click TCP/IP and then click Enable.

c. Make sure that the protocol order for TCP/IP is a smaller number that the named pipes or VIA protocols. Generally you should leave Shared Memory as order 1 and TCP/IP as order 2. Shared memory is only used when the client and
SQL Server are running on the same computer. All enabled protocols are tried in order until one succeeds, except that shared memory is skipped when the connection is not to the same computer. 


See Also

Another important place to find an extensive amount of SQL Server General & Database Engine related articles is the TechNet Wiki itself. The best entry point is SQL
Server General & Database Engine Resources on the TechNet Wiki


Приветствую всех посетителей сайта Info-Comp.ru! Сегодня мы рассмотрим ситуацию, когда Вы пытаетесь подключиться к Microsoft SQL Server по сети, но Вам это не удаётся, так как возникает та или иная ошибка подключения.

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

Не удается подключиться к Microsoft SQL Server по сети. Устраняем ошибку подключения

Итак, давайте начнем. Допустим, у нас есть Microsoft SQL Server, установленный на Windows, и мы будем пытаться подключится к нему по сети, например, из операционной системы Linux, используя Azure Data Studio.

Заметка! Как подключиться к Microsoft SQL Server из Linux.

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

Содержание

  1. Корректность ввода данных для подключения
  2. Доступность сервера по сети
  3. Открытые порты в брандмауэре
  4. Запущена ли служба «Обозреватель SQL Server»
  5. Запущена ли служба «SQL Server»
  6. Включен ли протокол «TCP/IP»
  7. Удаленные соединения с серверов
  8. Права имени входа, сопоставление с пользователем базы данных
  9. Подведение итогов

Корректность ввода данных для подключения

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

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

Имя экземпляра SQL Server необходимо указывать в тех случаях, когда у нас настроен именованный экземпляр, например, в редакции Express по умолчанию настраивается именованный экземпляр и динамические порты.

Если не указать имя экземпляра, когда это имя необходимо указывать, мы получим ошибку

«provider: TCP Provider, error: 40 – could not open a connection to SQL Server»

А если допустить ошибку в имени экземпляра, то

«provider: TCP Provider, error: 25 – connection string is not valid»

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

Скриншот 1

Заметка! Обзор инструментов для работы с Microsoft SQL Server.

Доступность сервера по сети

Если данные для подключения верны, то следующим шагом будет, конечно же, проверка доступности сервера, так как если сервер физически недоступен, то все следующие проверки будут абсолютно бесполезны и ни к чему не приведут.

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

«provider: TCP Provider, error: 25 – connection string is not valid»

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

Скриншот 2

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

Открытые порты в брандмауэре

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

Стандартный порт, на котором работает SQL Server, это 1433, соответственно, необходимо настроить правило для входящих подключений по порту 1433.

В случае если Вы используете именованный экземпляр SQL Server и динамические порты, то у Вас должно быть настроено правило для программы, в частности для исполняемого файла SQL Server – sqlservr.exe.

Для 2019 версии он расположен по следующему пути

Курс по SQL для начинающих

«C:Program FilesMicrosoft SQL ServerMSSQL15.MSSQLSERVERMSSQLBinnSqlservr.exe»

Кроме этого, в данном случае необходимо еще открыть UDP порт 1434 для службы «Обозреватель SQL Server».

Подробная официальная инструкция «Настройка брандмауэра Windows для доступа к SQL Server».

Продолжая тему именованных экземпляров и динамических портов, стоит отметить, что если используется именованный экземпляр и динамические порты, то дополнительно должна быть запущена служба «Обозреватель SQL Server». Если она не запущена, то подключиться Вы не сможете, будет возникать все та же ошибка

«provider: TCP Provider, error: 25 – connection string is not valid»

Поэтому запустите SQL Server Configuration Manager и проверьте соответствующую службу.

Скриншот 3

Запущена ли служба «SQL Server»

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

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

Поэтому проверяем, запущена ли служба «SQL Server» в SQL Server Configuration Manager.

Скриншот 4

Заметка! Сравнение Azure Data Studio с SQL Server Management Studio (SSMS).

Включен ли протокол «TCP/IP»

Кроме всего вышеперечисленного необходимо проверить, включен ли протокол «TCP/IP» в сетевой конфигурации SQL Server, так как если SQL Server используется в сети, данный протокол обязательно должен быть включен.

Это можно проверить в SQL Server Configuration Manager в разделе «Сетевая конфигурация SQL Server».

Скриншот 5

Удаленные соединения с серверов

Также необходимо проверить, разрешены ли удаленные соединения с серверов. Это можно сделать в SQL Server Management Studio в свойствах сервера на вкладке «Соединения», параметр «Разрешить удаленные соединения с сервером» должен быть включен.

Скриншот 6

Заметка! Как включить нумерацию строк кода в SQL Server Management Studio.

Права имени входа, сопоставление с пользователем базы данных

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

«При входе пользователя TestLogin произошла ошибка».

Поэтому необходимо проверить, сопоставлено ли имя входа с пользователем базы данных и предоставлены ли необходимые права.

Это можно сделать в SQL Server Management Studio, перейдите в контейнер «Безопасность -> Имена для входа», выберите нужное имя входа и зайдите в свойства этого имени. Затем на вкладке «Сопоставление пользователей» отметьте базы данных, с которыми будет сопоставлено данное имя входа, и задайте необходимые права в виде указания ролей базы данных.

Скриншот 7

Подведение итогов

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

Что необходимо сделать для устранения ошибки подключения к Microsoft SQL Server по сети:

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

Проверить доступность физического сервера по сети

Открыть порты в брандмауэре (файрволе)

Проверить, запущена ли служба «Обозреватель SQL Server»

Проверить, запущена ли служба «SQL Server»

Проверить, включен ли протокол «TCP/IP»

Проверить, разрешены ли удаленные соединения с серверов

Проверить права имени входа и сопоставить с пользователем базы данных

Заметка! Курсы по Transact-SQL для начинающих.

На сегодня это все, надеюсь, материал был Вам полезен, пока!

Содержание статьи:

    • SQL-сервер не найден или недоступен, ошибки соединения с SQL-сервером
      • Ошибка SQL-сервера 26
      • Ошибка SQL-сервера 18456
      • Не удалось запустить SQL-server — код ошибки 3417
    • Повреждена база данных
      • Код ошибки SQL-сервера 945
      • Код ошибки SQL-сервера 5172
      • Ошибка SQL-сервера 823
      • Ошибка SQL-сервера 8946
    • Другие ошибки SQL Server
      • Код ошибки SQL-сервера 1814
      • Код ошибки SQL-сервера 1067
      • SQL-сервер запускается, но работает слишком медленно
  • Если SQL-сервер не найден, убедитесь, что ваш экземпляр SQL-сервера действительно установлен и запущен. Для этого зайдите на компьютер, где он установлен, запустите диспетчер конфигурации SQL и проверьте, есть ли там тот экземпляр, к которому вы пытаетесь подключиться и запущен ли он. Нелишним будет также получить отчет об обнаружении компонентов SQL-серверов.
  • Если вы проделали п1. и не обнаружили источник проблемы, возможно, неверно указан IP-адрес компьютера или номер порта TCP. Перепроверьте их настройки.
  • Причиной того, что невозможно подключиться к SQL-серверу, также может быть сеть, убедитесь, что компьютер с SQL-сервером доступен по сети.
  • Проверьте, может ли клиентское приложение, установленное на том же компьютере, что и сервер, подключиться к SQL-серверу. Запустите SQL Server Management Studio(SSMS), в диалоговом окне “Подключиться к серверу” выберите тип сервера Database Engine, укажите способ аутентификации “Аутентификация Windows”, введите имя компьютера и экземпляра SQL-сервера. Проверьте подключение.

Обратите внимание, что многие сообщения об ошибках могут быть не показаны или не содержат достаточной информации для устранения проблемы. Это сделано из соображений безопасности, чтобы при попытке взлома злоумышленники не могли получить информацию об SQL-сервере. Полные сведения содержатся в логе ошибок, который обычно хранится по адресу C:Program FilesMicrosoft SQL ServerMSSQL13.MSSQLSERVERMSSQLLogERRORLOG, или там, куда его поместил администратор системы.

Ошибка SQL-сервера 26

Одна из наиболее часто встречающихся ошибок подключения к SQL-серверу, обычно связана с тем, что в настройках SQL-сервера не разрешены или ограничены удаленные соединения. Чтобы это исправить, попробуйте:

  • в SSMS в настройках SQL-сервера включите аутентификацию Windows
  • для брандмауэра Windows  создайте новое правило, которое разрешает подключение для всех программ и протоколов с указанного IP-адреса
  • убедитесь, что запущена служба SQL Server Browser

Ошибка SQL-сервера 18456

Эта ошибка означает, что попытка подключиться к серверу не успешна из-за проблем с именем пользователя или паролем. По коду ошибки в журнале ошибок можно узнать более точную причину, чтобы устранить ее.

Не удалось запустить SQL-server — код ошибки 3417

Возникает в случае, если были изменены настройки Windows или перемещена папка с файлами MSSQL.

  • зайдите в C:Program FilesMicrosoft SQLServerMSSQL.1MSSqLData — БезопасностьНастройки доступа — Учетная запись сетевой службы — добавьте учетную запись сетевой службы
  • проверьте, что MDF-файл не сжимается. Если это не так, отключите “Сжимать содержимое для экономии места на диске” в свойствах файла

Иногда ни один из этих способов не помогает, это значит, что файлы БД повреждены и ее придется восстанавливать из резервной копии.

Повреждена база данных

Код ошибки SQL-сервера 945

Ошибка 945 возникает, когда БД SQL-сервера помечена как IsShutdown. Проверьте, достаточно ли места на диске, достаточно ли прав у учетной записи для операций с БД, файлы MDF и LDF не должны быть помечены “Только для чтения”.

Код ошибки SQL-сервера 5172

SQL-сервер хранит свою физическую БД в первичном файле, в котором информация разбита постранично. Первая страница содержит информацию о заголовке mdf-файла и называется страницей заголовка. Она состоит из разнообразной информации о БД, такой как размер файла, подпись и т.д. В процессе прикрепления MDF на SQL-сервере часто возникает ошибка 5172. Это в основном происходит, если MDF-файл поврежден, информация в его заголовке тоже и соответственно сложно добраться до данных. Причиной может быть вирус, аварийное выключение системы, ошибка оборудования.

Ошибка SQL-сервера 823

SQL использует API Windows для операций ввода-вывода, но кроме завершения этих операций SQL проверяет все ошибки обращений к API. Если эти обращения несовместимы с ОС, появляется ошибка 823. Сообщение об ошибке 823 означает, что существует проблема с базовым оборудованием для хранения данных или с драйвером, который находится на пути запроса ввода-вывода. Пользователи могут столкнуться с этой ошибкой, если в файловой системе есть противоречия или поврежден файл базы данных.

Ошибка SQL-сервера 8946

Основной причиной ошибки 8946 так же, как и для 5172, является повреждение заголовков страниц БД SQL вследствие сбоя питания, вирусной атаки, отказа оборудования — SQL-сервер больше не может прочесть эти страницы.

Перечисленные ошибки 945, 5172, 823, 8946 можно устранить двумя методами:

  • если у вас есть свежая резервная копия базы — восстановить базу из этой копии
  • можно попробовать использовать специализированное ПО, такое как SQL Recovery Tool, чтобы восстановить поврежденные файлы

Желательно определить, что именно привело к возникновению ошибок и принять меры, чтобы это не повторялось — заменить плохо работающее оборудование, повысить информационную безопасность.

Другие ошибки SQL

Код ошибки SQL-сервера 1814

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

Код ошибки SQL-сервера 1067

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

SQL-сервер запускается, но работает слишком медленно

Проанализируйте журнал сервера, индексы (фрагментацию), запросы, задания, возможность взаимных блокировок.  Причин может быть масса.

Мы работаем с разными версиями SQL-сервера уже много лет, знакомы со всевозможными инструкциями SQL-сервера, видели самые разные варианты его настройки и использования на проектах у своих клиентов. В целом мы можем выделить четыре основных источника неполадок:

  • Индексы — причина проблем номер один. Неправильные индексы, отсутствующие индексы, слишком много индексов и подобное. Чаще всего при проблеме с индексами пользователи или администраторы базы данных не получают сообщения об ошибке, они просто видят, что база работает очень медленно и докопаться до причин бывает очень нелегко
  • изначально плохая архитектура сервера баз данных — ошибка, которую очень сложно и дорого исправлять на этапе, когда база уже используется
  • плохой код, в котором возможны блокировки и тупиковые места
  • использование конфигурации по умолчанию,

Если у вас не получается устранить ошибки сервера SQL-server самостоятельно, если они появляются снова и снова, то скорее всего в основе лежит одна из этих причин. В таком случае — если у вас произошла ошибка с SQL сервером, ваше ПО не видит SQL-сервер, либо нужно развернуть кластер SQL-серверов — вы всегда можете обратиться за консультацией и технической поддержкой к специалистам Интегруса, отправив заявку с сайта, написав на e-mail, либо позвонив в колл-центр нашей компании.

Присоединяйтесь к нам,

чтобы получать чек-листы, реальные кейсы, а также
обзоры сервисов раз в 2 недели.

Приветствую всех посетителей сайта Info-Comp.ru! Сегодня мы рассмотрим ситуацию, когда Вы пытаетесь подключиться к Microsoft SQL Server по сети, но Вам это не удаётся, так как возникает та или иная ошибка подключения.

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

Не удается подключиться к Microsoft SQL Server по сети. Устраняем ошибку подключения

Итак, давайте начнем. Допустим, у нас есть Microsoft SQL Server, установленный на Windows, и мы будем пытаться подключится к нему по сети, например, из операционной системы Linux, используя Azure Data Studio.

Заметка! Как подключиться к Microsoft SQL Server из Linux.

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

Содержание

  1. Корректность ввода данных для подключения
  2. Доступность сервера по сети
  3. Открытые порты в брандмауэре
  4. Запущена ли служба «Обозреватель SQL Server»
  5. Запущена ли служба «SQL Server»
  6. Включен ли протокол «TCP/IP»
  7. Удаленные соединения с серверов
  8. Права имени входа, сопоставление с пользователем базы данных
  9. Подведение итогов

Корректность ввода данных для подключения

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

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

Имя экземпляра SQL Server необходимо указывать в тех случаях, когда у нас настроен именованный экземпляр, например, в редакции Express по умолчанию настраивается именованный экземпляр и динамические порты.

Если не указать имя экземпляра, когда это имя необходимо указывать, мы получим ошибку

«provider: TCP Provider, error: 40 – could not open a connection to SQL Server»

А если допустить ошибку в имени экземпляра, то

«provider: TCP Provider, error: 25 – connection string is not valid»

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

Скриншот 1

Заметка! Обзор инструментов для работы с Microsoft SQL Server.

Доступность сервера по сети

Если данные для подключения верны, то следующим шагом будет, конечно же, проверка доступности сервера, так как если сервер физически недоступен, то все следующие проверки будут абсолютно бесполезны и ни к чему не приведут.

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

«provider: TCP Provider, error: 25 – connection string is not valid»

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

Скриншот 2

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

Открытые порты в брандмауэре

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

Стандартный порт, на котором работает SQL Server, это 1433, соответственно, необходимо настроить правило для входящих подключений по порту 1433.

В случае если Вы используете именованный экземпляр SQL Server и динамические порты, то у Вас должно быть настроено правило для программы, в частности для исполняемого файла SQL Server – sqlservr.exe.

Для 2019 версии он расположен по следующему пути

Курс по SQL для начинающих

«C:Program FilesMicrosoft SQL ServerMSSQL15.MSSQLSERVERMSSQLBinnSqlservr.exe»

Кроме этого, в данном случае необходимо еще открыть UDP порт 1434 для службы «Обозреватель SQL Server».

Подробная официальная инструкция «Настройка брандмауэра Windows для доступа к SQL Server».

Продолжая тему именованных экземпляров и динамических портов, стоит отметить, что если используется именованный экземпляр и динамические порты, то дополнительно должна быть запущена служба «Обозреватель SQL Server». Если она не запущена, то подключиться Вы не сможете, будет возникать все та же ошибка

«provider: TCP Provider, error: 25 – connection string is not valid»

Поэтому запустите SQL Server Configuration Manager и проверьте соответствующую службу.

Скриншот 3

Запущена ли служба «SQL Server»

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

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

Поэтому проверяем, запущена ли служба «SQL Server» в SQL Server Configuration Manager.

Скриншот 4

Заметка! Сравнение Azure Data Studio с SQL Server Management Studio (SSMS).

Включен ли протокол «TCP/IP»

Кроме всего вышеперечисленного необходимо проверить, включен ли протокол «TCP/IP» в сетевой конфигурации SQL Server, так как если SQL Server используется в сети, данный протокол обязательно должен быть включен.

Это можно проверить в SQL Server Configuration Manager в разделе «Сетевая конфигурация SQL Server».

Скриншот 5

Удаленные соединения с серверов

Также необходимо проверить, разрешены ли удаленные соединения с серверов. Это можно сделать в SQL Server Management Studio в свойствах сервера на вкладке «Соединения», параметр «Разрешить удаленные соединения с сервером» должен быть включен.

Скриншот 6

Заметка! Как включить нумерацию строк кода в SQL Server Management Studio.

Права имени входа, сопоставление с пользователем базы данных

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

«При входе пользователя TestLogin произошла ошибка».

Поэтому необходимо проверить, сопоставлено ли имя входа с пользователем базы данных и предоставлены ли необходимые права.

Это можно сделать в SQL Server Management Studio, перейдите в контейнер «Безопасность -> Имена для входа», выберите нужное имя входа и зайдите в свойства этого имени. Затем на вкладке «Сопоставление пользователей» отметьте базы данных, с которыми будет сопоставлено данное имя входа, и задайте необходимые права в виде указания ролей базы данных.

Скриншот 7

Подведение итогов

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

Что необходимо сделать для устранения ошибки подключения к Microsoft SQL Server по сети:

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

Проверить доступность физического сервера по сети

Открыть порты в брандмауэре (файрволе)

Проверить, запущена ли служба «Обозреватель SQL Server»

Проверить, запущена ли служба «SQL Server»

Проверить, включен ли протокол «TCP/IP»

Проверить, разрешены ли удаленные соединения с серверов

Проверить права имени входа и сопоставить с пользователем базы данных

Заметка! Курсы по Transact-SQL для начинающих.

На сегодня это все, надеюсь, материал был Вам полезен, пока!

title description ms.date ms.service ms.subservice ms.topic ms.assetid author ms.author

Troubleshoot Server & Database Connection Problems

In this article, diagnose and fix problems you experience when you’re connecting to a report server. Also learn about ‘Unexpected error’ messages.

12/16/2019

reporting-services

troubleshooting

conceptual

8bbb88df-72fd-4c27-91b7-b255afedd345

maggiesMSFT

maggies

Troubleshoot Server & Database Connection Problems with Reporting Services

Use this topic to troubleshoot problems that you experience when you’re connecting to a report server. This topic also provides information about «Unexpected error» messages. For more information about data source configuration and configuring report server connection information, see Specify Credential and Connection Information for Report Data Sources and Configure a Report Server Database Connection (Report Server Configuration Manager).

Cannot create a connection to data source ‘datasourcename’. (rsErrorOpeningConnection)

This is a generic error that occurs when the report server can’t open a connection to an external data source that provides data to a report. This error appears with a second error message that indicates the underlying cause. The following additional errors can appear with rsErrorOpeningConnection.

Login failed for user ‘UserName’

The user doesn’t have permission to access the data source. If you’re using a SQL Server database, verify that the user has a valid database user login. For more information about how to create a database user or a SQL Server login, see Create a Database User and Create a SQL Server Login.

Login failed for user ‘NT AUTHORITYANONYMOUS LOGON’

This error occurs when credentials are passed across multiple computer connections. If you’re using Windows Authentication, and the Kerberos version 5 protocol is not enabled, this error occurs when credentials are passed across more than one computer connection. To work around this error, consider using stored credentials or prompted credentials. For more information about how to work around this issue, see Specify Credential and Connection Information for Report Data Sources.

An error has occurred while establishing a connection to the server.

When you’re connecting to SQL Server, this failure may be caused by the fact that under the default settings SQL Server don’t allow remote connections. (provider: Named Pipes Provider, error: 40 — Could not open a connection to SQL Server). This error is returned by the instance of the Database Engine that hosts the report server database. In most cases, this error occurs because the SQL Server service is stopped. Or, if you’re using SQL Server Express with Advanced Services or a named instance, this error will occur if the report server URL or connection string for the report server database is not correct. To work through these issues, do the following:

  • Verify that the SQL Server (MSSQLSERVER) service is started. On the computer that hosts the instance of the Database Engine, click Start, click Administrative Tools, click Services, and scroll to SQL Server (MSSQLSERVER). If it is not started, right-click the service, select Properties, in Startup Type select Automatic, click Apply, click Start, and then click OK.
  • Verify that the report server URL and report server database connection string is correct. If Reporting Services or the Database Engine was installed as a named instance, the default connection string that is created during Setup will include the instance name. For example, if you installed a default instance of SQL Server Express with Advanced Services on a server named DEVSRV01, the web portal URL is DEVSRV01Reports$SQLEXPRESS. Furthermore, the database server name in the connection string will resemble DEVSRV01SQLEXPRESS. For more information about URLs and data source connection strings for SQL Server Express, see Reporting Services in SQL Server Express with Advanced Services. To verify the connection string for the report server database, start the Reporting Services Configuration tool and view the Database Setup page.

A connection can’t be made. Ensure that the server is running.

This error is returned by ADOMD.NET provider. There are several reasons why this error can occur. If you specified the server as «localhost», try specifying the server name instead. This error can also occur if memory can’t be allocated to the new connection. For more information, see Knowledge Base Article 912017 — Error message when you connect to an instance of SQL Server 2005 Analysis Services:.

If the error also includes «No such host is known», it indicates that the Analysis Services server is not available or is refusing the connection. If the Analysis Services server is installed as a named instance on a remote computer, you might have to run the SQL Server Browser service to get the port number used by that instance.

(Report Services SOAP Proxy Source)

If you get this error during report model generation, and the additional information section includes «SQL Server don’t exist or access denied», you might be encountering the following conditions:

  • The connection string for the data source includes «localhost».
  • TCP/IP is disabled for the SQL Server service.

To resolve this error, you can either modify the connection string to use the server name or you can enable TCP/IP for the service. Follow these steps to enable TCP/IP:

  1. Start SQL Server Configuration Manager.
  2. Expand SQL Server Network Configuration.
  3. Select Protocols for MSSQLSERVER.
  4. Right-click TCP/IP, and select Enable.
  5. Select SQL Server Services.
  6. Right-click SQL Server (MSSQLSERVER), and select Restart.

WMI error when connecting to a report server in Management Studio

By default, Management Studio uses the Reporting Services Windows Management Instrumentation (WMI) provider to establish a connection to the report server. If the WMI provider is not installed correctly, you will get the following error when attempting to connect to the report server:

Cannot connect to <your server name>. The Reporting Services WMI provider is not installed or is misconfigured (Microsoft.SqlServer.Management.UI.RSClient).

To resolve this error, you should reinstall the software. For all other cases, as a temporary work-around, you can connect to the report server through the SOAP endpoint:

  • In the Connect to Server dialog box in Management Studio, in Server Name, type the report server URL. By default, it is https://<your server name>/reportserver. Or if you’re using SQL Server 2008 Express with Advanced Services, it is https://<your server name>/reportserver$sqlexpress.

To resolve the error so that you can connect using the WMI provider, you should run Setup to repair Reporting Services, or reinstall Reporting Services.

Connection error, where login failed due to unknown user name or bad password

An rsReportServerDatabaseLogonFailed error can occur if you’re using a domain account for the connection from the report server to the report server database connection, and the password for the domain account has been changed.

The full error text is: «The report server can’t open a connection to the report server database. The logon failed (rsReportServerDatabaseLogonFailed). Logon failure: unknown user name or bad password.»

If you reset the password, you must update the connection. For more information, see Configure a Report Server Database Connection (Report Server Configuration Manager).

The report server can’t open a connection to the report server database. (rsReportServerDatabaseUnavailable).

Full Message: The report server can’t open a connection to the report server database. A connection to the database is required for all requests and processing. (rsReportServerDatabaseUnavailable)
This error occurs when the report server can’t connect to the SQL Server relational database that provides internal storage to the server. The connection to the report server database is managed through the Reporting Services Configuration tool. You can run the tool, go to the Database Setup page, and correct the connection information. Using the tool to update connection information is a best practice; the tool ensures that dependent settings are updated and that services are restarted. For more information, see Configure a Report Server Database Connection and Configure the Report Server Service Account.

This error can also occur if the Database Engine instance that hosts the report server database is not configured for remote connections. Remote connection is enabled by default in some editions of SQL Server. To verify whether it is enabled on the SQL Server Database Engine instance you’re using, run the SQL Server Configuration Manager tool. You must enable both TCP/IP and named pipes. A report server uses both protocols. For instructions on how to enable remote connections, see the section «How to Configure Remote Connections to the Report Server Database» in Configure a Report Server for Remote Administration.

If the error includes the following additional text, the password expired on the account used to run the Database Engine instance: «An error has occurred while establishing a connection to the server. When you’re connecting to SQL Server, this failure may be caused by the fact that under the default settings SQL Server don’t permit remote connections. (provider: SQL Server Network Interfaces, error: 26 — Error Locating Server/Instance Specified).» To resolve this error, reset the password.

«RPC Server is not listening»

The Report Server service uses Remote Procedure Call (RPC) server for some operations. If you get the «RPC Server is not listening» error, verify that the Report Server service is running.

Unexpected error (General network error)

This error indicates a data source connection error. You should check the connection string, and verify that you have permission to access the data source. If you’re using Windows Authentication to access a data source, you must have permission to access the computer that hosts the data source.

Unable to grant database access in SharePoint Central Administration

When you have configured Reporting Services to integrate with a SharePoint product or technology on Windows Vista or Windows Server 2008, you might receive the following error message when you try to grant access on the Grant Database Access page in SharePoint Central Administration: «A connection to the computer can’t be established.»

This happens because User Account Control (UAC) in Windows Vista and Windows Server 2008 requires explicit acceptance from an administrator to elevate and use the administrator token when performing tasks that require administrator permissions. In this case, however, the Windows SharePoint Services Administration service can’t be elevated to grant the Reporting Services service account or accounts access to the SharePoint configuration and content databases.

In SQL Server 2008 Reporting Services, only the Report Server service account requires database access; in SQL Server 2005 Reporting Services SP2, both the Report Server Windows service account and the Report Server Web service account require database access. For more information about the Report Server service account in SQL Server 2008, see Service Account (Reporting Services Configuration).

There are two workarounds for this issue.

  1. In one workaround, you can temporarily turn off UAC and use SharePoint Central Administration to grant access.

[!IMPORTANT]
Use caution if you turn off UAC to work around this issue, and turn on UAC immediately after you grant database access in SharePoint Central Administration. If you don’t want to turn off UAC, use the second workaround provided in this section. For information about UAC, see the Windows product documentation.

  1. In the second workaround, you can manually grant database access to the Reporting Services service account or accounts. You can use the following procedure to grant access by adding the Reporting Services service account or accounts to the correct Windows group and database roles. This procedure applies to the Report Server service account in SQL Server 2008 Reporting Services; if you’re running SQL Server 2005 Reporting Services, perform the procedure for the Report Server Windows service account and the Report Server Web service account.

To manually grant database access

  1. Add the Report Server service account to the WSS_WPG Windows group on the Reporting Services computer.
  2. Connect to the database instance that hosts the SharePoint configuration and content databases, and create a SQL database login for the Report Server service account.
  3. Add the SQL database login to the following database roles:
  • db_owner role in the WSS Content database
  • WSS_Content_Application_Pools role in the SharePoint_Config database

Unable to connect to the /reports and /reportserver directories when the report server databases are created on a virtual SQL Server that runs in a Microsoft Cluster Services (MSCS) cluster

When you create the report server databases, ReportServer and ReportServerTempDB, on a virtual SQL Server that runs in an MSCS cluster, the remote name in the format <domain><computer_name>$ might not be registered to SQL Server as a login. If you have configured the Report Server service account as an account that requires this remote name for connections, users can’t connect to the /reports and /reportserver directories in Reporting Services. For example, the built-in Windows account NetworkService requires this remote name. To avoid this issue, use an explicit domain account or a SQL Server login to connect to the report server databases.

See Also

Browser Support for Reporting Services
Errors and events (Reporting Services)
Troubleshoot Data Retrieval issues with Reporting Services Reports
Troubleshoot Reporting Services Subscriptions and Delivery

[!INCLUDEfeedback_stackoverflow_msdn_connect]

title description ms.date ms.service ms.subservice ms.topic ms.assetid author ms.author

Troubleshoot Server & Database Connection Problems

In this article, diagnose and fix problems you experience when you’re connecting to a report server. Also learn about ‘Unexpected error’ messages.

12/16/2019

reporting-services

troubleshooting

conceptual

8bbb88df-72fd-4c27-91b7-b255afedd345

maggiesMSFT

maggies

Troubleshoot Server & Database Connection Problems with Reporting Services

Use this topic to troubleshoot problems that you experience when you’re connecting to a report server. This topic also provides information about «Unexpected error» messages. For more information about data source configuration and configuring report server connection information, see Specify Credential and Connection Information for Report Data Sources and Configure a Report Server Database Connection (Report Server Configuration Manager).

Cannot create a connection to data source ‘datasourcename’. (rsErrorOpeningConnection)

This is a generic error that occurs when the report server can’t open a connection to an external data source that provides data to a report. This error appears with a second error message that indicates the underlying cause. The following additional errors can appear with rsErrorOpeningConnection.

Login failed for user ‘UserName’

The user doesn’t have permission to access the data source. If you’re using a SQL Server database, verify that the user has a valid database user login. For more information about how to create a database user or a SQL Server login, see Create a Database User and Create a SQL Server Login.

Login failed for user ‘NT AUTHORITYANONYMOUS LOGON’

This error occurs when credentials are passed across multiple computer connections. If you’re using Windows Authentication, and the Kerberos version 5 protocol is not enabled, this error occurs when credentials are passed across more than one computer connection. To work around this error, consider using stored credentials or prompted credentials. For more information about how to work around this issue, see Specify Credential and Connection Information for Report Data Sources.

An error has occurred while establishing a connection to the server.

When you’re connecting to SQL Server, this failure may be caused by the fact that under the default settings SQL Server don’t allow remote connections. (provider: Named Pipes Provider, error: 40 — Could not open a connection to SQL Server). This error is returned by the instance of the Database Engine that hosts the report server database. In most cases, this error occurs because the SQL Server service is stopped. Or, if you’re using SQL Server Express with Advanced Services or a named instance, this error will occur if the report server URL or connection string for the report server database is not correct. To work through these issues, do the following:

  • Verify that the SQL Server (MSSQLSERVER) service is started. On the computer that hosts the instance of the Database Engine, click Start, click Administrative Tools, click Services, and scroll to SQL Server (MSSQLSERVER). If it is not started, right-click the service, select Properties, in Startup Type select Automatic, click Apply, click Start, and then click OK.
  • Verify that the report server URL and report server database connection string is correct. If Reporting Services or the Database Engine was installed as a named instance, the default connection string that is created during Setup will include the instance name. For example, if you installed a default instance of SQL Server Express with Advanced Services on a server named DEVSRV01, the web portal URL is DEVSRV01Reports$SQLEXPRESS. Furthermore, the database server name in the connection string will resemble DEVSRV01SQLEXPRESS. For more information about URLs and data source connection strings for SQL Server Express, see Reporting Services in SQL Server Express with Advanced Services. To verify the connection string for the report server database, start the Reporting Services Configuration tool and view the Database Setup page.

A connection can’t be made. Ensure that the server is running.

This error is returned by ADOMD.NET provider. There are several reasons why this error can occur. If you specified the server as «localhost», try specifying the server name instead. This error can also occur if memory can’t be allocated to the new connection. For more information, see Knowledge Base Article 912017 — Error message when you connect to an instance of SQL Server 2005 Analysis Services:.

If the error also includes «No such host is known», it indicates that the Analysis Services server is not available or is refusing the connection. If the Analysis Services server is installed as a named instance on a remote computer, you might have to run the SQL Server Browser service to get the port number used by that instance.

(Report Services SOAP Proxy Source)

If you get this error during report model generation, and the additional information section includes «SQL Server don’t exist or access denied», you might be encountering the following conditions:

  • The connection string for the data source includes «localhost».
  • TCP/IP is disabled for the SQL Server service.

To resolve this error, you can either modify the connection string to use the server name or you can enable TCP/IP for the service. Follow these steps to enable TCP/IP:

  1. Start SQL Server Configuration Manager.
  2. Expand SQL Server Network Configuration.
  3. Select Protocols for MSSQLSERVER.
  4. Right-click TCP/IP, and select Enable.
  5. Select SQL Server Services.
  6. Right-click SQL Server (MSSQLSERVER), and select Restart.

WMI error when connecting to a report server in Management Studio

By default, Management Studio uses the Reporting Services Windows Management Instrumentation (WMI) provider to establish a connection to the report server. If the WMI provider is not installed correctly, you will get the following error when attempting to connect to the report server:

Cannot connect to <your server name>. The Reporting Services WMI provider is not installed or is misconfigured (Microsoft.SqlServer.Management.UI.RSClient).

To resolve this error, you should reinstall the software. For all other cases, as a temporary work-around, you can connect to the report server through the SOAP endpoint:

  • In the Connect to Server dialog box in Management Studio, in Server Name, type the report server URL. By default, it is https://<your server name>/reportserver. Or if you’re using SQL Server 2008 Express with Advanced Services, it is https://<your server name>/reportserver$sqlexpress.

To resolve the error so that you can connect using the WMI provider, you should run Setup to repair Reporting Services, or reinstall Reporting Services.

Connection error, where login failed due to unknown user name or bad password

An rsReportServerDatabaseLogonFailed error can occur if you’re using a domain account for the connection from the report server to the report server database connection, and the password for the domain account has been changed.

The full error text is: «The report server can’t open a connection to the report server database. The logon failed (rsReportServerDatabaseLogonFailed). Logon failure: unknown user name or bad password.»

If you reset the password, you must update the connection. For more information, see Configure a Report Server Database Connection (Report Server Configuration Manager).

The report server can’t open a connection to the report server database. (rsReportServerDatabaseUnavailable).

Full Message: The report server can’t open a connection to the report server database. A connection to the database is required for all requests and processing. (rsReportServerDatabaseUnavailable)
This error occurs when the report server can’t connect to the SQL Server relational database that provides internal storage to the server. The connection to the report server database is managed through the Reporting Services Configuration tool. You can run the tool, go to the Database Setup page, and correct the connection information. Using the tool to update connection information is a best practice; the tool ensures that dependent settings are updated and that services are restarted. For more information, see Configure a Report Server Database Connection and Configure the Report Server Service Account.

This error can also occur if the Database Engine instance that hosts the report server database is not configured for remote connections. Remote connection is enabled by default in some editions of SQL Server. To verify whether it is enabled on the SQL Server Database Engine instance you’re using, run the SQL Server Configuration Manager tool. You must enable both TCP/IP and named pipes. A report server uses both protocols. For instructions on how to enable remote connections, see the section «How to Configure Remote Connections to the Report Server Database» in Configure a Report Server for Remote Administration.

If the error includes the following additional text, the password expired on the account used to run the Database Engine instance: «An error has occurred while establishing a connection to the server. When you’re connecting to SQL Server, this failure may be caused by the fact that under the default settings SQL Server don’t permit remote connections. (provider: SQL Server Network Interfaces, error: 26 — Error Locating Server/Instance Specified).» To resolve this error, reset the password.

«RPC Server is not listening»

The Report Server service uses Remote Procedure Call (RPC) server for some operations. If you get the «RPC Server is not listening» error, verify that the Report Server service is running.

Unexpected error (General network error)

This error indicates a data source connection error. You should check the connection string, and verify that you have permission to access the data source. If you’re using Windows Authentication to access a data source, you must have permission to access the computer that hosts the data source.

Unable to grant database access in SharePoint Central Administration

When you have configured Reporting Services to integrate with a SharePoint product or technology on Windows Vista or Windows Server 2008, you might receive the following error message when you try to grant access on the Grant Database Access page in SharePoint Central Administration: «A connection to the computer can’t be established.»

This happens because User Account Control (UAC) in Windows Vista and Windows Server 2008 requires explicit acceptance from an administrator to elevate and use the administrator token when performing tasks that require administrator permissions. In this case, however, the Windows SharePoint Services Administration service can’t be elevated to grant the Reporting Services service account or accounts access to the SharePoint configuration and content databases.

In SQL Server 2008 Reporting Services, only the Report Server service account requires database access; in SQL Server 2005 Reporting Services SP2, both the Report Server Windows service account and the Report Server Web service account require database access. For more information about the Report Server service account in SQL Server 2008, see Service Account (Reporting Services Configuration).

There are two workarounds for this issue.

  1. In one workaround, you can temporarily turn off UAC and use SharePoint Central Administration to grant access.

[!IMPORTANT]
Use caution if you turn off UAC to work around this issue, and turn on UAC immediately after you grant database access in SharePoint Central Administration. If you don’t want to turn off UAC, use the second workaround provided in this section. For information about UAC, see the Windows product documentation.

  1. In the second workaround, you can manually grant database access to the Reporting Services service account or accounts. You can use the following procedure to grant access by adding the Reporting Services service account or accounts to the correct Windows group and database roles. This procedure applies to the Report Server service account in SQL Server 2008 Reporting Services; if you’re running SQL Server 2005 Reporting Services, perform the procedure for the Report Server Windows service account and the Report Server Web service account.

To manually grant database access

  1. Add the Report Server service account to the WSS_WPG Windows group on the Reporting Services computer.
  2. Connect to the database instance that hosts the SharePoint configuration and content databases, and create a SQL database login for the Report Server service account.
  3. Add the SQL database login to the following database roles:
  • db_owner role in the WSS Content database
  • WSS_Content_Application_Pools role in the SharePoint_Config database

Unable to connect to the /reports and /reportserver directories when the report server databases are created on a virtual SQL Server that runs in a Microsoft Cluster Services (MSCS) cluster

When you create the report server databases, ReportServer and ReportServerTempDB, on a virtual SQL Server that runs in an MSCS cluster, the remote name in the format <domain><computer_name>$ might not be registered to SQL Server as a login. If you have configured the Report Server service account as an account that requires this remote name for connections, users can’t connect to the /reports and /reportserver directories in Reporting Services. For example, the built-in Windows account NetworkService requires this remote name. To avoid this issue, use an explicit domain account or a SQL Server login to connect to the report server databases.

See Also

Browser Support for Reporting Services
Errors and events (Reporting Services)
Troubleshoot Data Retrieval issues with Reporting Services Reports
Troubleshoot Reporting Services Subscriptions and Delivery

[!INCLUDEfeedback_stackoverflow_msdn_connect]

Обработка исключений

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

Для получения специализированных сообщений при возникновении ошибок подключения к базе данных Microsoft SQL Server используются классы SqlException и SqlErro r. Объекты этих классов можно применять для перехвата номеров ошибок, возвращаемых базой данных (таблица 4.2):

Таблица
4.2.
Ошибки SQL Server

Номер ошибки Описание
17 Неверное имя сервера
4060 Неверное название базы данных
18456 Неверное имя пользователя или пароль

Дополнительно вводятся уровни ошибок SQL Server, позволяющие охарактеризовать причину проблемы и ее сложность (таблица 4.3):

Таблица
4.3.
Уровни ошибок SQL Server

Интервал возвращаемых значений Описание Действие
11-16 Ошибка, созданная пользователем Пользователь должен повторно ввести верные данные
17-19 Ошибки программного обеспечения или оборудования Пользователь может продолжать работу, но некоторые запросы будут недоступны. Соединение остается открытым
20-25 Ошибки программного обеспечения или оборудования Сервер закрывает соединение. Пользователь должен открыть его снова

Создайте новое Windows-приложение и назовите его «ExceptionsSQL». Свойству Size формы устанавливаем значение «600;380». Добавляем на форму элемент управления DataGrid, его свойству Dock устанавливаем значение «Fill». Перетаскиваем элемент Panel, определяем следующие его свойства:

panel1, свойство Значение
Dock Right
Location 392; 0
Size 200; 346

На панели размещаем четыре текстовых поля, надпись и кнопку:

textBox1, свойство Значение
Name txtDataSource
Location 8; 8
Size 184; 20
Text Введите название сервера
textBox2, свойство Значение
Name txtInitialCatalog
Location 8; 40
Size 184; 20
Text Введите название базы данных
textBox3, свойство Значение
Name txtUserID
Location 8; 72
Size 184; 20
Text Введите имя пользователя
textBox4, свойство Значение
Name txtPassword
Location 8; 104
Size 184; 20
Text Введите пароль1Для скрывания пароля при вводе можно в свойстве «PasswordChar» текстового поля ввести заменяющий символ, например, звездочку («*»).
label1, свойство Значение
Location 16; 136
Size 176; 160
Text
button1, свойство Значение
Name btnConnect
Location 56; 312
Size 96; 23
Text Соединение

Интерфейс приложения готов. Подключаем пространство имен для работы с базой данных:

using System.Data.SqlClient;

Объекты ADO .NET и весь блок обработки исключений помещаем в обработчик кнопки «Соединение»:

private void btnConnect_Click(object sender, System.EventArgs e)
{
	SqlConnection conn = new SqlConnection();
	label1.Text = "";
	try
	{
//conn.ConnectionString = "workstation id=9E0D682EA8AE448;data source="(local)
//";" + "persist security info=True;initial catalog=Northwind;
//user id=sa;password=12345";

//Строка ConnectionString в качестве параметров 
//будет передавать значения, введенные в текстовые поля:
		conn.ConnectionString = 
		"initial catalog=" + txtInitialCatalog.Text + ";" +
		"user id=" + txtUserID.Text + ";" +
		"password=" + txtPassword.Text + ";" +
		"data source=" + txtDataSource.Text + ";" +
		"workstation id=9E0D682EA8AE448;persist security info=True;";
		SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT * FROM 
		 Customers", conn);
		DataSet ds = new DataSet();
		conn.Open();
		dataAdapter.Fill(ds);
		dataGrid1.DataSource = ds.Tables[0].DefaultView;
	}
	catch (SqlException OshibkiSQL)
	{
		foreach (SqlError oshibka in OshibkiSQL.Errors)
		{
			//Свойство Number объекта oshibka возвращает 
			//номер ошибки SQL Server
			switch (oshibka.Number)
			{
			case 17:
			label1.Text += "nНеверное имя сервера!";
			break;
			case 4060:
			label1.Text += "nНеверное имя базы данных!";
			break;
			case 18456:
			label1.Text += "nНеверное имя пользователя или пароль!";
			break;
			}
			//Свойство Class объекта oshibka возвращает 
			//уровень ошибки SQL Server,
			//а свойство Message - уведомляющее сообщение
			label1.Text +="n"+oshibka.Message + "
			 Уровень ошибки SQL Server: " + oshibka.Class;			}
	}
	//Отлавливаем прочие возможные ошибки:
	catch (Exception ex)
	{
		label1.Text += "nОшибка подключения: " + ex.Message;
	}
	finally
	{
		conn.Dispose();
	}
}

Закомментированная строка подключения содержит обычное перечисление параметров. При отладке приложения будет легче сначала добиться наличия подключения, а затем осуществлять привязку параметров, вводимых в текстовые поля. Запускаем приложение. При вводе неверных параметров в надпись выводятся соответствующие сообщения, а при правильных параметрах элемент DataGrid отображает данные (рис. 4.11):

В программном обеспечении к курсу вы найдете приложение Exceptions SQL (CodeGlava2 ExceptionsSQL).

Скопируйте папку приложения ExceptionsSQL и назовите ее «ExceptionsMDB». Удаляем с панели на форме имеющиеся текстовые поля и добавляем три новых:

textBox1, свойство Значение
Name txtDataBasePassword
Location 8; 16
Size 184; 20
Text Введите пароль базы данных
textBox2, свойство Значение
Name txtUserID
Location 8; 48
Size 184; 20
Text Введите имя пользователя
textBox3, свойство Значение
Name TxtPassword
Location 8; 80
Size 184; 20
Text Введите пароль пользователя

Изменяем пространство имен для работы с базой данных:

Обработчик кнопки «Соединение» будет выглядеть так:

private void btnConnect_Click(object sender, System.EventArgs e)
{
	OleDbConnection conn = new OleDbConnection();
	label1.Text = "";
	try
	{
// conn.ConnectionString = @"Provider=""Microsoft.Jet.OLEDB.4.0"";
//Data Source=""D:UchebnikCodeGlava2BDwithUsersP.mdb"";
Jet OLEDB:System database=""D:UchebnikCodeGlava2BDWorkFile.mdw"";
User ID=Adonetuser;Password=12345;Jet OLEDB:Database Password=98765;";
				
//Строка ConnectionString в качестве параметров 
//будет передавать значения, введенные в текстовые поля:
		conn.ConnectionString = 
		"Jet OLEDB:Database Password=" + txtDataBasePassword.Text 
		 + ";" + "User ID=" + txtUserID.Text + ";" +
		 "password=" + txtPassword.Text + ";" +

				@"Provider=""Microsoft.Jet.OLEDB.4.0"";Data 		
	Source=""D:UchebnikCodeGlava2BDwithUsersP.mdb"";
Jet OLEDB:System database=""D:UchebnikCodeGlava
BDWorkFile.mdw"";";

		OleDbDataAdapter dataAdapter = 
		 new OleDbDataAdapter("SELECT * FROM Туристы", conn);
		DataSet ds = new DataSet();
		conn.Open();
		dataAdapter.Fill(ds);
		dataGrid1.DataSource = ds.Tables[0].DefaultView;
	}
	catch (OleDbException oshibka)
	{
		//Пробегаем по всем ошибкам
		for (int i=0; i < oshibka.Errors.Count; i++)
		{
			label1.Text+= "Номер ошибки " + i 
			 + "n" + "Сообщение: " + 
			 oshibka.Errors[i].Message + "n" +
			 "Номер ошибки NativeError: " + 
			 oshibka.Errors[i].NativeError + "n" +
			 "Источник: " + oshibka.Errors[i].Source + 
			 "n" + "Номер SQLState: " + 
			 oshibka.Errors[i].SQLState + "n";
			}
		}
		//Отлавливаем прочие возможные ошибки:
		catch (Exception ex)
		{
			label1.Text += "nОшибка подключения: " + 
			 ex.Message;
		}
		finally
		{
			conn.Dispose();
		}
}

Запускаем приложение (рис. 4.12). Свойство Message возвращает причину ошибки на русском языке, поскольку установлена русская версия Microsoft Office 2003. Свойство NativeError (внутренняя ошибка) возвращает номер исключения, генерируемый самим источником данных. Вместе или по отдельности со свойством SQL State их можно использовать для создания переключателя, предоставляющего пользователю расширенную информацию (мы это делали в приложении ExceptionsSQL) .

Готовое приложение ExceptionsMDB

Рис.
4.12.
Готовое приложение ExceptionsMDB

Кроме обработки исключений, здесь следует обратить внимание на интерфейс, предоставляющий возможность пользователю вводить сведения своей учетной записи. Теперь в целях безопасности приложения не нужно включать пароль в код при использовании мастеров, поскольку строка соединения будет генерироваться динамически. Разумеется, ваше приложение может иметь другой интерфейс — например, окно соединения будет появляться в дочерней форме.

В программном обеспечении к курсу вы найдете приложение Exceptions MDB (CodeGlava2 ExceptionsMDB).

Вопрос:

Возникают проблемы при подключении к SQL Server, при этом в сообщении об ошибке встречается фрагмент:

  1. «Ошибка подключения к серверу

    SQL

    «;

  2. «Ошибка подключения к экземпляру сервера

    SQL

    «;

  3. «При установлении соединения с

    SQL

    Server произошла ошибка, связанная с сетью или определенным экземпляром. Сервер не найден или недоступен»;

  4. «Error 26»;

  5. «Error: 40».

Что можно сделать для решения таких проблем?

Ответ:

Для устранения проблемы попробуйте воспользоваться приведенной ниже инструкцией.

Инструкция по устранению наиболее часто возникающих проблем с подключением к SQL Server:

1) Проверьте, что имя сервера задано верно (в частности, если компьютер был переименован):


Также проверьте, что имя экземпляра (в данном случае – SQLEXPRESS) задано верно. При необходимости допишите его вручную в поле «Сервер баз данных».
Примечание. Если SQL Server был установлен автоматически при установке Business Studio, то имя экземпляра должно быть SQLEXPRESS.

2) Если сервер SQL находится не на локальном компьютере, то проверьте, что компьютер включен и подключен к сети.

3) Проверьте, что SQL Server запущен и настроен верно. Далее приведен пример для SQL Server 2014 (подходит и для других версий SQL Server, начиная с 2008)1):

a. Откройте Пуск->Все программы->Microsoft SQL Server 2014->Диспетчер конфигурации SQL Server 2014.

b. Проверьте, что запущена служба SQL Server (на скриншоте пример для экземпляра SQLEXPRESS), т.е. что она находится в состоянии «Работает»:

c. Проверьте, что запущена служба обозревателя SQL Server (SQL Server Browser), т.е. что она находится в состоянии «Работает»:

d. Проверьте, что удаленные соединения разрешены, т.е. что состояние протоколов «Именованные каналы» и «TCP/IP» для рассматриваемого экземпляра SQL Server – «Включено»:

4) Проверьте, что никакие брандмауэры на компьютере с сервером SQL не блокируют соединение со службой SQL. То же касается и антивирусов, т.к. некоторые из них имеют функции брандмауэров. Обратитесь к документации по этим средствам. Для проверки можно временно отключить их.
Далее приведен пример для встроенного брандмауэра Windows 7:

a. Откройте Пуск->Панель управления->Брандмауэр Windows, перейдите на закладку «Разрешить запуск программы или компонента через брандмауэр Windows» (для Windows 10 необходимо вызвать контекстное меню правой кнопкой мыши от кнопки «Пуск»->Сетевые подключения->Брандмауэр Windows->Брандмауэр и безопасность сети->Разрешить работу с приложением через брандмауэр) и нажмите кнопку «Изменить параметры».

b. Добавьте следующие программы, как показано на рисунке (повторив поз. 1-3 для каждой из программ)2):

  • C:Program Files (x86)Microsoft

    SQL

    ServerMSSQL12.SQLEXPRESSMSSQLBinnsqlservr.exe (служба SQL Server)

  • C:Program Files (x86)Microsoft

    SQL

    Server90Sharedsqlbrowser.exe (cлужба обозревателя SQL Server)

c. Перезапустите вышеуказанные службы.

5) Возможно, имеются проблемы с разрешением сетевых имен. Попробуйте в окне Свойств подключения к базе данных в поле «Сервер базы данных» указать вместо имени компьютера его IP-адрес. Например, так:

В случае локального сервера SQL укажите IP-адрес 127.0.0.1, в случае удаленного – узнайте у администратора сети.

6) Если ничего не помогает, воспользуйтесь полной статьей от Microsoft по данной теме. Если на компьютере, где находится

SQL

Server, соединение успешно — можно сразу перейти к Шагу 9 статьи от Microsoft.

Внимание! Выполнение данных действий может потребовать квалификации и полномочий системного администратора.

When I experienced this error in Visual Studio,

“A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 — Could not open a connection to SQL Server)”

…it was during the execution of the following C# code, which was attempting to obtain my SQL Server data to display it in a grid. The break occurred exactly on the line that says connect.Open():

        using (var connect = Connections.mySqlConnection)
        {
            const string query = "SELECT Name, Birthdate, Narrative FROM Friends";
            using (var command = new SqlCommand(query, connect))
            {
                connect.Open();
                using (var dr = command.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        // blah
                    }
                }
            }
        }

It was inexplicable because the SQL query was very simple, I had the right connection string, and the database server was available. I decided to run the actual SQL query manually myself in SQL Management Studio and it ran just fine and yielded several records. But one thing stood out in the query results: there was some improperly encoded HTML text inside a varchar(max) type field within the Friends table (specifically, some encoded comment symbols of the sort <!-- lodged within the «Narrative» column’s data). The suspect data row looked like this:

Name    Birthdate    Narrative
====    =========    ============== 
Fred    21-Oct-79    &lt;!--HTML Comment -->Once upon a time...

Notice the encoded HTML symbol «&lt;«, which stood for a «<» character. Somehow that made its way into the database and my C# code could not pick it up! It failed everytime right at the connect.Open() line! After I manually edited that one row of data in the database table Friends and put in the decoded «<» character instead, everything worked! Here’s what that row should have looked like:

Name    Birthdate    Narrative
====    =========    ============== 
Fred    21-Oct-79    <!--HTML Comment -->Once upon a time...

I edited the one bad row I had by using this simple UPDATE statement below. But if you had several offending rows of encoded HTML, you might need a more elaborate UPDATE statement that uses the REPLACE function:

UPDATE Friends SET Narrative = '<!--HTML Comment -->Once upon a time...' WHERE Narrative LIKE '&lt%'

So, the moral of the story is (at least in my case), sanitize your HTML content before storing it in the database and you won’t get this cryptic SQL Server error in the first place! (Uh, properly sanitizing/decoding your HTML content is the subject of another discussion worthy of a separate StackOverflow search if you need more information!)

  • Ошибка подключения к апп стор
  • Ошибка подключения к usbasp 3 ch341a
  • Ошибка подключения к tsl серверу
  • Ошибка подключения к sql серверу 18456
  • Ошибка подключения к smtp серверу сообщение не было отправлено