sqldataadapter在PowerShell中不起作用。

huangapple go评论102阅读模式
英文:

sqldataadapter is not working in powershell

问题

请查找发出数据库选择查询的代码部分。
我正在将输出加载到一个表中,但不起作用。
选择查询没问题,因为我在数据库中运行相同的查询并得到1行输出。

  1. $SqlQuery = "select InputFiles,OutputFiles from $mastTableNm where JobName = '$jobname'";
  2. $sqloutqryreader = MsSqlQueryExecutor $SqlQuery $logfile 'SELECT'
  3. Add-Content -Value "$TimeinSec Log: Reading data from sql reader" -Path $logfile
  4. $mstrtab = new-object System.Data.DataTable
  5. $mstrtab.Load($sqloutqryreader)
  6. echo $mstrtab
  7. ForEach($mstrjobrw in $mstrtab)
  8. {
  9. Add-Content -Value "$TimeinSec Log: Reading data from sql reader $mstrjobrw.InputFiles $mstrjobrw.OutputFiles " -Path $logfile
  10. }

以下是执行查询并返回适配器的函数。

  1. function Global:MsSqlQueryExecutor(
  2. $SqlQuery,
  3. $logfile,
  4. $QueryType
  5. )
  6. {
  7. $Global:sqloutput = $Null
  8. try
  9. {
  10. # 确保以下代码块的输出不会污染返回值
  11. $Null = @(
  12. Add-Content -Value "$TimeinSec Log: Setting up the sql query to execute" -Path $logfile
  13. $SQLUsername = "aa"
  14. $SQLPassword = "aa"
  15. $Database = "aa"
  16. $SQLServer = "aa.aa.aa.windows.net"
  17. # 定义与 SQL 数据库的连接
  18. $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
  19. $SqlConnection.ConnectionString = "Server=$SQLServer;Database=$Database;User ID=$SQLUsername;Password=$SQLPassword;Trusted_Connection=False;Encrypt=True;Connection Timeout=5000;"
  20. $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
  21. $SqlCmd.CommandText = $SqlQuery
  22. $SqlCmd.Connection = $SqlConnection
  23. $SqlCmd.CommandType = [System.Data.CommandType]::Text
  24. $SqlCmd.CommandTimeout = 0
  25. Add-Content -Value "$TimeinSec Log: Preparation to execute query: $SqlQuery is completed" -Path $logfile
  26. if ($SqlConnection.State -eq [System.Data.ConnectionState]'Closed')
  27. {
  28. $SqlConnection.Open()
  29. }
  30. if ($QueryType -eq 'SELECT')
  31. {
  32. $adp = New-Object System.Data.SqlClient.SqlDataAdapter $SqlCmd
  33. $dtst = New-Object System.Data.DataSet
  34. $adp.Fill($dtst)
  35. $Global:sqloutput = $dtst.Tables[0]
  36. Add-Content -Value "$TimeinSec Log: Execution of the $QueryType query: $SqlQuery completed successfully." -Path $logfile
  37. }
  38. else
  39. {
  40. $Global:sqloutput = $SqlCmd.ExecuteReader()
  41. Add-Content -Value "$TimeinSec Log: Execution of the $QueryType query: $SqlQuery completed successfully." -Path $logfile
  42. }
  43. )
  44. return $Global:sqloutput
  45. }
  46. catch
  47. {
  48. Add-Content -Value "$TimeinSec Error: Failed to Query: $SqlQuery" -Path $logfile
  49. Add-Content -Value $_.Exception.Message -Path $logfile
  50. EXIT
  51. }
  52. finally
  53. {
  54. $SqlConnection.Close()
  55. $SqlConnection.Dispose();
  56. Add-Content -Value "$TimeinSec Cleanup: Connection is disposed" -Path $logfile
  57. }
  58. }

表格没有加载。

我尝试了另一种解决方法,也不起作用。

请查看这个问题的链接:

https://stackoverflow.com/questions/59611471/read-method-inside-sqldatareader-in-powershell-is-not-working-with-while-loop?noredirect=1#comment105386383_59611471

英文:

please find the code that issues a select query to data base.
I am loading the output to a table which is not working
The select query is fine as I run the same query in database and get 1 row as output.

  1. $SqlQuery = "select InputFiles,OutputFiles from $mastTableNm where JobName = '$jobname'";
  2. $sqloutqryreader = MsSqlQueryExecutor $SqlQuery $logfile 'SELECT'
  3. Add-Content -Value "$TimeinSec Log: Reading data from sql reader" -Path $logfile
  4. $mstrtab = new-object System.Data.DataTable
  5. $mstrtab.Load($sqloutqryreader)
  6. echo $mstrtab
  7. ForEach($mstrjobrw in $mstrtab)
  8. {
  9. Add-Content -Value "$TimeinSec Log: Reading data from sql reader $mstrjobrw.InputFiles $mstrjobrw.OutputFiles " -Path $logfile
  10. }

Following is the function that executes the query and returns the adapter.

  1. function Global:MsSqlQueryExecutor(
  2. $SqlQuery,
  3. $logfile,
  4. $QueryType
  5. )
  6. {
  7. $Global:sqloutput = $Null
  8. try
  9. {
  10. # make sure that the output from the following code block does not pollute return value
  11. $Null = @(
  12. Add-Content -Value "$TimeinSec Log: Setting up the sql query to execute" -Path $logfile
  13. $SQLUsername = "aa"
  14. $SQLPassword = "aa"
  15. $Database = "aa"
  16. $SQLServer = "aa.aa.aa.windows.net"
  17. # Define the connection to the SQL Database
  18. $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
  19. $SqlConnection.ConnectionString = "Server=$SQLServer;Database=$Database;User ID=$SQLUsername;Password=$SQLPassword;Trusted_Connection=False;Encrypt=True;Connection Timeout=5000;"
  20. $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
  21. $SqlCmd.CommandText = $SqlQuery
  22. $SqlCmd.Connection = $SqlConnection
  23. $SqlCmd.CommandType = [System.Data.CommandType]::Text
  24. $SqlCmd.CommandTimeout = 0
  25. Add-Content -Value "$TimeinSec Log: Preparation to execute query: $SqlQuery is completed" -Path $logfile
  26. if ($SqlConnection.State -eq [System.Data.ConnectionState]'Closed')
  27. {
  28. $SqlConnection.Open()
  29. }
  30. if ($QueryType -eq 'SELECT')
  31. {
  32. $adp = New-Object System.Data.SqlClient.SqlDataAdapter $SqlCmd
  33. $dtst = New-Object System.Data.DataSet
  34. $adp.Fill($dtst)
  35. $Global:sqloutput = $dtst.Tables[0]
  36. Add-Content -Value "$TimeinSec Log: Execution of the $QueryType query: $SqlQuery completed successfully." -Path $logfile
  37. }
  38. else
  39. {
  40. $Global:sqloutput = $SqlCmd.ExecuteReader()
  41. Add-Content -Value "$TimeinSec Log: Execution of the $QueryType query: $SqlQuery completed successfully." -Path $logfile
  42. }
  43. )
  44. return $Global:sqloutput
  45. }
  46. catch
  47. {
  48. Add-Content -Value "$TimeinSec Error: Failed to Query: $SqlQuery" -Path $logfile
  49. Add-Content -Value $_.Exception.Message -Path $logfile
  50. EXIT
  51. }
  52. finally
  53. {
  54. $SqlConnection.Close()
  55. $SqlConnection.Dispose();
  56. Add-Content -Value "$TimeinSec Cleanup: Connection is disposed" -Path $logfile
  57. }
  58. }

The table is not getting loaded.

I tried another workaround which is also not working.

Please find the link to that question

https://stackoverflow.com/questions/59611471/read-method-inside-sqldatareader-in-powershell-is-not-working-with-while-loop?noredirect=1#comment105386383_59611471

答案1

得分: 1

你可以首先尝试使用ExecuteReader()方法来填充数据表的简单代码片段,看看基本查询是否返回任何数据或不返回。

  1. $jobname = "<jobname>"
  2. $mastTableNm = "<tablename>"
  3. $sqlConn = New-Object System.Data.SqlClient.sqlConnection "<Your Connection String Here>"
  4. $sqlConn.Open()
  5. $sqlCommand = $sqlConn.CreateCommand()
  6. $sqlCommand.CommandText = "select InputFiles, OutputFiles from $mastTableNm where JobName = '$jobname'"
  7. Write-Host $sqlCommand.CommandText
  8. $result = $sqlCommand.ExecuteReader()
  9. $dtTable = New-Object System.Data.DataTable
  10. $dtTable.Load($result)

这段代码用于执行数据库查询并将结果填充到数据表中。

英文:

Can you try with simple code snippet first with ExecuteReader() to populate the datatable? See if the basic query is returning any data or not,

  1. $jobname = &quot;&lt;jobname&gt;&quot;
  2. $mastTableNm = &quot;&lt;tablename&gt;&quot;
  3. $sqlConn = New-Object System.Data.SqlClient.sqlConnection &quot;&lt;Your Connection String Here&gt;&quot;;
  4. $sqlConn.Open();
  5. $sqlCommand = $sqlConn.CreateCommand();
  6. $sqlCommand.CommandText = &quot;select InputFiles,OutputFiles from $mastTableNm where JobName = &#39;$jobname&#39;&quot;;
  7. Write-Host $sqlCommand.CommandText;
  8. $result = $sqlCommand.ExecuteReader();
  9. $dtTable = New-Object System.Data.DataTable;
  10. $dtTable.Load($result);

答案2

得分: 0

以下是您要翻译的部分:

问题出在返回值上。PowerShell有一些让人讨厌的返回行为。我使用了一个解决方法来使我的代码工作。我用一个全局变量来初始化数据表,而不是使用返回值。然后在需要的代码中访问这个全局变量。

  1. function Global:MsSqlQueryExecutor(
  2. $SqlQuery,
  3. $logfile,
  4. $QueryType
  5. )
  6. {
  7. try
  8. {
  9. # 确保以下代码块的输出不会污染返回值
  10. $Null = @(
  11. Add-Content -Value " $TimeinSec 日志:设置要执行的SQL查询" -Path $logfile
  12. $SQLUsername = "aaa"
  13. $SQLPassword = "aaa"
  14. $Database = "aaa"
  15. $SQLServer = "aaat"
  16. # 定义与SQL数据库的连接
  17. $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
  18. $SqlConnection.ConnectionString = "Server=$SQLServer;Database=$Database;User ID=$SQLUsername;Password=$SQLPassword;Trusted_Connection=False;Encrypt=True;Connection Timeout=5000;"
  19. $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
  20. $SqlCmd.CommandText = $SqlQuery
  21. $SqlCmd.Connection = $SqlConnection
  22. $SqlCmd.CommandType = [System.Data.CommandType]::Text
  23. $SqlCmd.CommandTimeout = 0
  24. Add-Content -Value " $TimeinSec 日志:准备执行查询:$SqlQuery 已完成" -Path $logfile
  25. if ($SqlConnection.State -eq [System.Data.ConnectionState]'Closed')
  26. {
  27. $SqlConnection.Open()
  28. }
  29. if ($QueryType -eq 'SELECT')
  30. {
  31. $adp = New-Object System.Data.SqlClient.SqlDataAdapter $SqlCmd
  32. $dtst = New-Object System.Data.DataSet
  33. $adp.Fill($dtst)
  34. $Global:sqlexecoutput = $dtst.Tables[0]
  35. Add-Content -Value " $TimeinSec 日志:$QueryType 查询的执行:$SqlQuery 已成功完成。" -Path $logfile
  36. }
  37. else
  38. {
  39. $Global:sqlexecoutput = $SqlCmd.ExecuteReader()
  40. Add-Content -Value " $TimeinSec 日志:$QueryType 查询的执行:$SqlQuery 已成功完成。" -Path $logfile
  41. }
  42. )
  43. }
  44. catch
  45. {
  46. Add-Content -Value " $TimeinSec 错误:查询失败:$SqlQuery" -Path $logfile
  47. Add-Content -Value $_.Exception.Message -Path $logfile
  48. 退出
  49. }
  50. finally
  51. {
  52. $SqlConnection.Close()
  53. $SqlConnection.Dispose();
  54. Add-Content -Value " $TimeinSec 清理:连接已释放" -Path $logfile
  55. }
  56. }
英文:

The issue was with return. Powershell has some annoying return behaviour. I used a workaround to make my code work. instead of return I used a global variable to initialize the datatable. This global variable was then accessed in the code where i need.

  1. function Global:MsSqlQueryExecutor(
  2. $SqlQuery,
  3. $logfile,
  4. $QueryType
  5. )
  6. {
  7. try
  8. {
  9. # make sure that the output from the following code block does not pollute return value
  10. $Null = @(
  11. Add-Content -Value &quot;$TimeinSec Log: Setting up the sql query to execute&quot; -Path $logfile
  12. $SQLUsername = &quot;aaa&quot;
  13. $SQLPassword = &quot;aaa&quot;
  14. $Database = &quot;aaa&quot;
  15. $SQLServer = &quot;aaat&quot;
  16. # Define the connection to the SQL Database
  17. $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
  18. $SqlConnection.ConnectionString = &quot;Server=$SQLServer;Database=$Database;User ID=$SQLUsername;Password=$SQLPassword;Trusted_Connection=False;Encrypt=True;Connection Timeout=5000;&quot;
  19. $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
  20. $SqlCmd.CommandText = $SqlQuery
  21. $SqlCmd.Connection = $SqlConnection
  22. $SqlCmd.CommandType = [System.Data.CommandType]::Text
  23. $SqlCmd.CommandTimeout = 0
  24. Add-Content -Value &quot;$TimeinSec Log: Preparation to execute query: $SqlQuery is completed&quot; -Path $logfile
  25. if ($SqlConnection.State -eq [System.Data.ConnectionState]&#39;Closed&#39;)
  26. {
  27. $SqlConnection.Open()
  28. }
  29. if ($QueryType -eq &#39;SELECT&#39;)
  30. {
  31. $adp = New-Object System.Data.SqlClient.SqlDataAdapter $SqlCmd
  32. $dtst = New-Object System.Data.DataSet
  33. $adp.Fill($dtst)
  34. $Global:sqlexecoutput = $dtst.Tables[0]
  35. Add-Content -Value &quot;$TimeinSec Log: Execution of the $QueryType query: $SqlQuery completed successfully.&quot; -Path $logfile
  36. }
  37. else
  38. {
  39. $Global:sqlexecoutput = $SqlCmd.ExecuteReader()
  40. Add-Content -Value &quot;$TimeinSec Log: Execution of the $QueryType query: $SqlQuery completed successfully.&quot; -Path $logfile
  41. }
  42. )
  43. }
  44. catch
  45. {
  46. Add-Content -Value &quot;$TimeinSec Error: Failed to Query: $SqlQuery&quot; -Path $logfile
  47. Add-Content -Value $_.Exception.Message -Path $logfile
  48. EXIT
  49. }
  50. finally
  51. {
  52. $SqlConnection.Close()
  53. $SqlConnection.Dispose();
  54. Add-Content -Value &quot;$TimeinSec Cleanup: Connection is disposed&quot; -Path $logfile
  55. }
  56. }

huangapple
  • 本文由 发表于 2020年1月6日 23:21:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/59614633.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定