[英]Return output from SQL Command in Powershell using c# classes
I am running a Powershell script that is able to execute SQL queries using the c# classes:我正在运行一个 Powershell 脚本,该脚本能够使用 c# 类执行 SQL 查询:
$MasterDatabaseConnection = New-Object System.Data.SqlClient.SqlConnection
$MasterDatabaseConnection.ConnectionString = "<Connectionstring>"
$MasterDatabaseConnection.Open()
#Create & Run query
$MasterDatabaseCommand = New-Object System.Data.SqlClient.SqlCommand
$MasterDatabaseCommand.Connection = $MasterDatabaseConnection
$MasterDatabaseCommand.CommandTimeout = 1200;
$MasterDatabaseCommand.CommandText = "select top 1 * from TestTable"
$Results = $MasterDatabaseCommand.ExecuteNonQuery()
$Results
However, How can I get the function ExecuteNonQuery() to return the actual output of the row I am fetching?但是,如何让 function ExecuteNonQuery() 返回我正在获取的行的实际 output? It only returns the success or not of the query.它只返回查询是否成功。
I cannot solve this by using other powershell-modules or c# programs.我无法通过使用其他 powershell 模块或 c# 程序来解决这个问题。
ExecuteNonQuery
doesn't return rows . ExecuteNonQuery
不返回 rows 。 The clue is the "non query" part (it is intended for state-change operations that do not yield rows - UPDATE
, for example).线索是“非查询”部分(它用于不产生行的状态更改操作 - 例如UPDATE
)。 You want ExecuteReader
for row-based data, or ExecuteScalar
for a single cell (the first column of the first row of the first grid).您需要ExecuteReader
用于基于行的数据,或ExecuteScalar
用于单个单元格(第一个网格的第一行的第一列)。 With ExecuteReader
, a typical usage would be (in no specific language):使用ExecuteReader
,典型用法是(没有特定语言):
reader = command.ExecuteQuery()
while reader.Read()
# look at reader reader.GetValues(), reader[index], reader.GetValue(column),
# or reader.GetString(), reader.GetInt32(), etc
If the query could contain multiple grids, this extends to如果查询可能包含多个网格,这将扩展到
reader = command.ExecuteQuery()
do
while reader.Read()
# the same per-grid code as before
while reader.NextResult()
(ie the per-row Read()
calls preceed each row, and the per-grid NextResult()
calls follow each grid consumed) (即每行Read()
调用在每行之前,每网格NextResult()
调用遵循每个消耗的网格)
Note that all of the connection, the command, and the reader implement IDisposable
, and should be disposed after use.请注意,所有的连接、命令和阅读器都实现了IDisposable
,并且应该在使用后被释放。 If this is a simple batch script that will terminate entirely when exiting, you might get away with not doing this (relying on process tear-down instead).如果这是一个简单的批处理脚本,将在退出时完全终止,您可能会不这样做(而是依靠进程拆除)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.