Powershell output insert into remote database server ERROR - sql

I use the following command to connect to remote database:
$SQLServer = "Servername"
$SQLDBName = "DBname"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; User ID= username; Password= password"
$SqlConnection.Open()
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "INSERT INTO dbo.Tablename(ReceivedTime, Subject)VALUES($time, $subject)"
$SqlCmd.Connection = $SqlConnection
But have the following err message:
Exception calling "Open" with "0" argument(s): "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)" At line:10 char:1
$conn.Open()
~~~~~~~~~~~~
CategoryInfo : NotSpecified: (:) [], MethodInvocationException
FullyQualifiedErrorId : SqlException
I need to connect to the remote server and online solutions mainly focus on the local servers, so they are not suitable for me. (Company server/database and network, maybe different from local server?)
Hope you can help me improve the code or provide with some solutions. Thanks all.

Related

bcp to extract data from SQL query to local machine

I am using below code
bcp "SELECT COL1 FROM DBO.V_VIEW_1" queryout d:\VIEW_PART1.csv -S AB6Y7YYY,1433 -c -t",", -T
AB6Y7YYY : I got this with below code in SSMS
SELECT ##SERVERNAME
I am able to see VIEW_PART1.csv in d drive but it is empty and error in command line is as below
SQLState = 08001, NativeError = 10061
Error = [Microsoft][ODBC Driver 17 for SQL Server]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online.
SQLState = S1T00, NativeError = 0
Error = [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired
What am i doing wrong?

PowerShell: network-related or instance-specific error occurred while establishing a connection to SQL Server

On my Skype For Business Server, when I run the following command, my Queue get's changed as it should:
Set-CsRgsQueue -Instance $queue
On my linked server however (one hop away from the Lync server), i get the following error:
network-related or instance-specific error occurred while
establishing a connection to SQL Server. Set-CsRgsQueue : 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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
I am however able to set up ODBC to the remote server (+ opened FW 1433 port, restarted the service ,....)
Where could my problem be?
EDIT:
My scriptblock looks like:
import-module Lync
$queue = Get-CsRgsQueue -Name $toChange
$action = New-CsRgsCallAction -Action TransferToPSTN -Uri $forwarduri -QueueID $queue.Identity
$queue.OverflowAction = $action
$queue.OverflowThreshold = 0
Set-CsRgsQueue -Instance $queue
If i'm not able to solve the issue, how could I implement invoke-command as this works on the server itself?
I tried by doing:
Invoke-Command -ComputerName SQLSERVER -ScriptBlock {Set-CsRgsQueue -Instance $queue}
but this throws:
Cannot validate argument on parameter 'Instance'. The argument is null. Provide a valid value for the argument, and then try running the command again.

Can't connect to SQL from Powershell

I tried to query my syslogins with this script in powershell. It gives me this error:
"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.
The error shown:
provider: Named Pipes Provider, error: 40 - Could not open a
connection to SQL Server
Remote Access is enabled on the Database I try to connect to.
This is the code im working with:
$conn = New-Object System.Data.SqlClient.SqlConnection
$cmd = New-Object System.Data.SqlClient.SqlCommand
$conn.ConnectionString = "server=servername.hsr.ch;database=mydb;Integrated Security=true;"
$conn.open()
$cmd.Connection = $conn
$cmd.CommandText = "SELECT * FROM syslogins"
$out = $cmd.ExecuteNonQuery()
$conn.close()
print $out

Powershell SMO Can't Connect

I'm having an issue connecting to a SQL Server using SMO when using a ServerConnection. For the last few months this has been working, but now failing. Here is a snippet of the script:
$svrname = "Server"
#Establish Server connection
Write-ColorOutput "Establishing SQL Server Connection to $svrName" "White"
$mysvrConn = new-object Microsoft.SqlServer.Management.Common.ServerConnection
$mysvrConn.ServerInstance=$svrName
$mysvrConn.LoginSecure = $false
$mysvrConn.Login = "Admin"
$mysvrConn.Password = "Password"
$svr = new-object 'Microsoft.SqlServer.Management.SMO.Server' $mysvrConn
However, the following works.
$svrname = "Server"
$svr = new-object ('Microsoft.SQLServer.Management.SMO.Server') $svrname
And the assemblies:
Write-ColorOutput "Loading assemblies" "White"
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SQLServer.Smo") | out-null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | out-null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") | out-null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoEnum") | Out-Null
You almost certainly have permission issues with your SQL login. You are either using the wrong password, or the login does not have the proper creds.
Embarrassingly, when I had this issue, it turned out to be that I had entered the login password incorrectly.
I had expected a specific error stating the login failed. Instead it was the more generic: Failed to connect to server localhost., which threw me off.
Like you, I ran a test with the $LoginSecure = $True which worked, telling me that the connection to the server was fine. Only then did I spot my typo and was on my way to SMO bliss.

What would be a connection string for Ironpython to connect to a SQL Server CE?

I'm working with Visual Studio to connect to an IronPython application to a local .sdf database. However, I get this error:
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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
Here's my code:
import wpf
import os
import ConfigParser
import clr
clr.AddReference('System.Data')
from System.Data.SqlClient import SqlConnection, SqlParameter
...
conn_string = "Data Source=" + AppData + "local.static.sdf;Password=[PASSWORD];Persist Security Info=True"
connection = SqlConnection(conn_string)
connection.Open()
command = connection.CreateCommand()
command.CommandText = 'select nom from employee where id = #id'
command.Parameters.Add(SqlParameter('id', 1))
reader = command.ExecuteReader()
buff = ''
while reader.Read():
buff = reader['id']
print buff
connection.Close()
Anyone has an idea about what is going wrong with this piece of code?
Thank you!
~Stéphane
Interesting scenario, wonder if you can make it work...
You need
clr.AddReference('System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91')
and
from System.Data.SqlServerCe import SqlCeConnection, SqlCeParameter