我试图从名为mailing_list_membership的表中获取名为list_name的列的前二十行的值。

$DBConnectionString = "Driver={PostgreSQL ANSI(x64)};Server=$MyServer;Port=$MyPort;Database=$MyDB;Uid=$MyUid;Pwd=$MyPass;"
$DBConn = New-Object System.Data.Odbc.OdbcConnection;
$DBConn.ConnectionString = $DBConnectionString;
$DBConn.Open();
$DBCmd = $DBConn.CreateCommand();

$DBCmd.CommandText = "SELECT list_name FROM mailing_list_membership LIMIT 20";
$list_name_rows_value  =  $DBCmd.ExecuteReader();

Write-output  $list_name_rows_value
$DBConn.Close();

但是,在powershell中,变量list_name_rows_value仅返回字段计数。
FieldCount
----------
     1
     1
     1
     1
     1
     1
     1
     1
     1
     1
     1
     1
     1
     1
     1
     1
     1
     1
     1

最佳答案

使用SqlDataReader对象,您需要自己遍历结果集,例如像这样:

$rdr = $DBCmd.ExecuteReader()
while ($rdr.Read()) {
  $rdr.GetValue(0)
}

让阅读器填写可以使用常规Format-* cmdlet显示的数据表更为方便:
$rdr = $DBCmd.ExecuteReader()
$tbl = New-Object Data.DataTable
$tbl.Load($rdr)
$rdr.Close()

$tbl | Format-Table -AutoSize

09-26 22:48