我正在使用PowerShell连接到SQLServer数据库。我运行SQL代码的脚本工作正常但是它定期生成所需的输出失败,然后再次运行它工作正常。
$mySQLQuery = "SQL Query Here"
$myDataSet = New-Object System.Data.DataSet "myDataResultSet"
$sqlConn = New-Object System.Data.SqlClient.SqlConnection("Data Source=myDataSource;Initial Catalog=myDBServer;Integrated Security = False; User ID = UserName; Password =PassWord;")
$SqlConn.ConnectionTimeout= 0
$adapter = New-Object System.Data.SqlClient.SqlDataAdapter($mySQLQuery, $sqlConn)
$adapter.Fill($myDataSet)
$SqlConn.Close()
虽然搜索和阅读我发现它与连接超时有关。我尝试将sql连接超时从默认设置为30设置为0,但在运行scirpt时我收到错误,如下所示:
$sqlConn.ConnectionTimeout = 0 is read-only property.
知道我在这里做错了吗?
谢谢。
答案 0 :(得分:1)
解决此问题的最简单方法是将;Connection Timeout=60
添加到连接字符串中。
$sqlConn = New-Object System.Data.SqlClient.SqlConnection('Connection Timeout=60')
$sqlConn.ConnectionTimeout
60
你可能不希望它设置为0,如果你需要一个非常高的值,可以使用300或者其他东西。
答案 1 :(得分:1)
Personally, I set the Command Timeout, rather than the connection...
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = "<yourconnectionstring>"
$command = $connection.CreateCommand()
$command.CommandText = "<yoursql>"
$command.CommandTimeout = 0
$results = $command.ExecuteReader()
$table = New-Object System.Data.DataTable
$table.Load($results)
$connection.Dispose()