Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test Database Connectivity

Tags:

powershell

Is there an easy way to test the connectivity to a MS SQL Server instance from a client (without loading any SQL assemblies) with PowerShell?

MS Sql: Servername\Instance Port 1433

How can I test the connectivity to the server with PowerShell from a normal client?

like image 652
LaPhi Avatar asked Mar 24 '15 09:03

LaPhi


People also ask

How do you test network connectivity issues to a database?

To test the connection to your database, run the telnet hostname port on your Looker server. For example, if you are running MySQL on the default port and your database name is mydb, the command would be telnet mydb 3306 .

How can I check connection between database and server?

How to Check Connectivity between Application Server and Database Server. Simply, you can use Ping cmdlet to verify that the Application Server can communicate and reach properly with the Database Server over the network.


2 Answers

Use the SqlConnection class to test a connection. You don't have to load any SQL assemblies.

Helper function:

function Test-SQLConnection {         [OutputType([bool])]     Param     (         [Parameter(Mandatory=$true,                     ValueFromPipelineByPropertyName=$true,                     Position=0)]         $ConnectionString     )     try     {         $sqlConnection = New-Object System.Data.SqlClient.SqlConnection $ConnectionString;         $sqlConnection.Open();         $sqlConnection.Close();          return $true;     }     catch     {         return $false;     } } 

Usage example:

Test-SQLConnection "Data Source=localhost;database=myDB;User ID=myUser;Password=myPassword;" 
like image 62
Martin Brandl Avatar answered Oct 14 '22 14:10

Martin Brandl


That depends on what you actually want to test. If you just want to verify that you can connect to the port on the remote host something like this will do:

$server = 'servername' $port   = 1433  $tcp = New-Object Net.Sockets.TcpClient if ([void]$tcp.Connect($server, $port)) {   'connected' } else {   'not connected' } $tcp.Dispose() 

If you want to verify that a connection to an SQL Server instance can be established you'll need something like this:

$dbhost = 'servername' $dbinst = 'instance' $dbname = 'master'  $username = ... $password = ...  $cs = "Server=$dbhost\$dbinst;Database=$dbname;User Id=$username;" +       "Password=$password;"  $cn = New-Object -COM 'ADODB.Connection' $cn.ConnectionString = $cs try {   $cn.Open()   if ($cn.State -eq 1) {     'connected'     $cn.Close()   } else {     'not connected'   } } catch {   'not connected' } 
like image 35
Ansgar Wiechers Avatar answered Oct 14 '22 15:10

Ansgar Wiechers