Microsoft / msphpsql

Can not connect to MS SQL from Ubuntu sqlcmd client #470

I’m trying to connect to SQLExpress server from a Linux Ubuntu 16.04 computer. I Installed all SQL commad line utilities for the linux machine and follow instructions from Microsoft MSSQL on Linux docs.

When i run sqlcmd — S ip/SQLEXPRESS — U SA — P 1234, the command always returns the following error :

Sqlcmd: Error: Microsoft ODBC Driver 13 for SQL Server : Login timeout expired.
Sqlcmd: Error: Microsoft ODBC Driver 13 for SQL Server : TCP Provider: Error code 0x2AF9

I was able to run the same command from a Windows10 computers and it works with no flaws.

The linux computer can communicate to the server machine and mssql 1433 port. I test this with the linux nc command (netcat).

Linux nc command results:
nc — z — v — w5 192.168.0.1 1433
Connection to 192.168.0.1 1433 port [tcp/ms-sql-s] succeeded!

Any suggestions or something missing?

Please I will really appreciate any help.

The text was updated successfully, but these errors were encountered:

david-puglielli commented Jul 11, 2017

Hi @CarlosRPEvertsz, it looks like you are trying to connect to a named instance. You need to supply the port number when connecting to a named instance:

sqlcmd — S <IP>\\SQLEXPRESS,1433 — U .

For more info please see #442 and this page.

Please let us know if this fixes the problem.

david-puglielli commented Jul 13, 2017

Hi @leandroruel could you elaborate? What are you trying to do, what is failing, what is the error message(s) and what is the expected outcome? Is it similar to what @CarlosRPEvertsz is seeing?

meet-bhagdev commented Jul 13, 2017

@leandroruel @CarlosRPEvertsz What version of the ODBC Driver and sqlcmd are you using?

CarlosRPEvertsz commented Jul 14, 2017

The ODBC version is 13 (Both Linux Ubuntu and Windows 10). The Win10 ODBC works perfectly but Linux (Ubuntu) version don’t.

I wish to test previous versions to see but don’t know where could i find them for Linux.

Thank you for your question and help.
Regards,
Carlos

david-puglielli commented Jul 14, 2017

Also, please look at the troubleshooting section in that link — in particular, make sure you are using only one copy of the driver manager, as multiple copies can cause problems.

leandroruel commented Jul 17, 2017 •

guys, i give up. it’s really hard make this driver works properly on ubuntu. i’m trying for 3 days without success, installed ubuntu ina machine using virtualbox, installed the driver and only the php 7 driver following all instructions, after this i get:

everytime i install the driver, the sqlcmd command dont work anymore, like this was uninstalled

CarlosRPEvertsz commented Jul 17, 2017

I ‘m trying to install in fresh ubuntu 16.04 standalone computer and it doesn’t work. Complete 13.0-13.1 versions/revisions does not work. I think there is something wrong when microsoft developers built/compiled these revisions for ubuntu distro. Perhaps it works on other linux like red hat, but ubuntu 16.04 doesn’t.

leandroruel commented Jul 17, 2017

good luck, all my attempts fails

meet-bhagdev commented Jul 17, 2017

@leandroruel @CarlosRPEvertsz I will work with you to make sure we can get sqlcmd working on Ubuntu 16.04. Are you able to re install it on a fresh machine? We can do a debugging screenshare session where I can help you fix this issue if you like.

leandroruel commented Jul 17, 2017 •

i already made a fresh installation, but i can do another again without the drivers installed

meet-bhagdev commented Jul 17, 2017

Sounds good! Send me an email at meetb@microsoft. com and I will setup a screenshare session with you. ?

meet-bhagdev commented Jul 17, 2017

@CarlosRPEvertsz I worked with @leandroruel to look into this using a screenshare. I can do the same for you :) Send me an email at meetb@microsoft. com and I will set something up.

leandroruel commented Jul 18, 2017

yes, i was able of connect to a remote database from my ubuntu machine using the driver, but in my company network, something is blocking me of connect to the database from my VM, and the funny part is, from my PC (host) i can connect to the database normally, my (guest) VM ubuntu always return the error:

romulofrt commented Jul 18, 2017 •

Hi @meet-bhagdev , i had same problem with @leandroruel(his works with me). We were create new VM with Windows and access connection ready sucessfully, but when we try connection in VM based Linux(Ubuntu 16.04) we get the error:

image

All the settings for remote connections in SQL Server are enable.

image

image

meet-bhagdev commented Jul 18, 2017

@romulofrt as I told @leandroruel the problem is with SQL Server not allow remote connections/firewall setup/other networking issue.

If I give you my SQL Server ip (which is what I did with @leandroruel), it works fine. Did you enable remote access for SQL Server?

romulofrt commented Jul 18, 2017 •

But the problem isn’t SQL Server, because on VM based in Windows the connection has successfuly.

Do you agree if problem is with SQL Server both VM aren’t connected ?

meet-bhagdev commented Jul 18, 2017

@romulofrt I do not quite follow. What do you mean by the VM based in Windows has a successful connection? Is this an Ubuntu VM in Windows? I am happy to setup a screen share with you to troubleshoot this.

romulofrt commented Jul 18, 2017

So you would like to do the troubleshoot ? By Skype ? If yes, i already sent invite.

meet-bhagdev commented Jul 18, 2017

@romulofrt I did not get it. Can you send me an email at meetb@microsoft. com? I will set something up

leandroruel commented Jul 19, 2017 •

@meet-bhagdev thanks for all ur help, now i’m able of connect to the database of my company, the issue was. the port 1433 for any reason are blocked to connect, and the sql server uses a dinamic port so, the infrastructure department made all to me, allowing me to connect to the sql server. i don’t know how to explain it to you, because, i’m from another department, but i think my issue was related with this: https://docs. microsoft. com/pt-br/sql/sql-server/install/configure-the-windows-firewall-to-allow-sql-server-access

romulofrt commented Jul 19, 2017

@meet-bhagdev You really were right! It was a SQL Server-specific port in Windows Server 2012 R2.
Thanks a lot for the help.

JanOonk commented Jan 9, 2018 •

I had the same problem trying to connect with:
sqlcmd — S <ip>\\SQLEXPRESS,1433 — U username — P password

from a Ubuntu v16 to Windows SQL Server. Strange thing was that I could connect by using a Windows 8 Client and SQL Management Studio.
The fix for letting the Ubuntu client connect was to set «Listen to All» to No in the SQL Server Configuration Manager > SQL Server Network Configuration > Protocols for [instance name].
And under IP Address change 127.0.0.1 to the [ip] used to connect.
Don’t forget to restart the SQL Server!

Other tip: check your firewall (or temporaly disable it for testing).
Also allow remote connections in SQL Server properties > Connections. See above posts.

Life safer was this command: nc — zv <ip> 1433
It should say Connection to 1433 port [tcp/ms-sql-s] succeeded!

MySQL — система управления базами данных (СУБД) с открытым исходным кодом от компании Oracle. Она была разработана и оптимизирована специально для работы веб-приложений. MySQL является неотъемлемой частью таких веб-сервисов, как Facebook, Twitter, Wikipedia, YouTube и многих других.

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

Не удаётся подключиться к локальному серверу

Одной из распространённых ошибок подключения клиента к серверу является «ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld. sock’ (2)».

Эта ошибка означает, что на хосте не запущен сервер MySQL ( mysqld ) или вы указали неправильное имя файла сокета Unix или порт TCP/IP при попытке подключения.

Убедитесь, что сервер работает. Проверьте процесс с именем mysqld на хосте сервера, используя команды ps или grep, как показано ниже.

Если эти команды не показывают выходных данных, то сервер БД не работает. Поэтому клиент не может подключиться к нему. Чтобы запустить сервер, выполните команду systemctl.

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

Если в результате выполнения команды произошла ошибка службы MySQL, вы можете попробовать перезапустить службу и ещё раз проверить её состояние.

Если сервер работает (как показано) и вы по-прежнему видите эту ошибку, вам следует проверить, не заблокирован ли порт TCP/IP брандмауэром или любой другой службой блокировки портов.

Piano , Казань , По итогам собеседования

Для поиска порта, который прослушивается сервером, используйте команду netstat .

Не удаётся подключиться к серверу MySQL

Ещё одна похожая и часто встречающаяся ошибка подключения — «(2003) Can’t connect to MySQL server on ‘server’ (10061)». Это означает, что в сетевом соединении было отказано.

Следует проверить, работает ли в системе сервер MySQL (смотрите выше) и на тот ли порт вы подключаетесь (как найти порт, можно посмотреть выше).

Похожие частые ошибки, с которыми вы можете столкнуться при попытке подключиться к серверу MySQL:

Ошибки запрета доступа в MySQL

В MySQL учётная запись (УЗ) определяется именем пользователя и клиентским хостом, с которого пользователь может подключиться. УЗ может также иметь данные для аутентификации (например, пароль).

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

В MySQL есть возможность создавать учётные записи, позволяющие пользователям клиентских программ подключаться к серверу и получать доступ к данным. Поэтому при ошибке доступа проверьте разрешение УЗ на подключение к серверу через клиентскую программу.

Увидеть разрешённые привилегии учётной записи можно, выполнив в консоли команду SHOW GRANTS
Входим в консоль (пример для Unix, для Windows консоль можно найти в стартовом меню):

В консоли вводим команду:

Дать привилегии конкретному пользователю в БД по IP-адресу можно, используя следующие команды:

Ошибки запрещённого доступа могут также возникнуть из-за проблем с подключением к MySQL (см. выше).

Потеря соединения с сервером MySQL

С этой ошибкой можно столкнуться по одной из следующих причин:

  • плохое сетевое соединение;
  • истекло время ожидания соединения;
  • размер BLOB больше, чем max_allowed_packet .

В первом случае убедитесь, что у вас стабильное сетевое подключение (особенно, если подключаетесь удалённо).

Если проблема с тайм-аутом соединения (особенно при первоначальном соединении MySQL с сервером), увеличьте значение параметра connect_timeout .

В случае с размером BLOB нужно установить более высокое значение для max_allowed_packet в файле конфигурации /etc/my. cnf в разделах [mysqld] или [client] как показано ниже.

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

Слишком много подключений

Эта ошибка означает, что все доступные соединения используются клиентскими программами. Количество соединений (по умолчанию 151) контролируется системной переменной max_connections . Устранить проблему можно, увеличив значение переменной в файле конфигурации /etc/my. cnf .

Недостаточно памяти

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

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

  • если клиент MySQL используется напрямую, запустите его с ключом —quick switch , чтобы отключить кешированные результаты;
  • если вы используете драйвер MyODBC, пользовательский интерфейс (UI) имеет расширенную вкладку с опциями. Отметьте галочкой «Do not cache result» (не кешировать результат).

Также может помочь MySQL Tuner. Это полезный скрипт, который подключается к работающему серверу MySQL и даёт рекомендации по настройке для более высокой производительности.

MySQL продолжает «падать»

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

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

Чтобы узнать время безотказной работы сервера, запустите команду mysqladmin .

Кроме того, можно остановить сервер, сделать отладку MySQL и снова запустить службу. Для отображения статистики процессов MySQL во время выполнения других процессов откройте окно командной строки и введите следующее:

Заключение

Самое важное при диагностике — понять, что именно вызвало ошибку. Следующие шаги помогут вам в этом:

Источники:

https://github. com/microsoft/msphpsql/issues/470

https://tproger. ru/translations/troubleshoot-common-errors-in-mysql/

Понравилась статья? Поделиться с друзьями:
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: