如何在PowerShell中用函数将MySQL查询结果传入ConsoleGuiTools的TextField
PowerShell中使用Microsoft.PowerShell.ConsoleGuiTools无法将MySQL查询结果填充到TextField控件
我尝试借助Microsoft.PowerShell.ConsoleGuiTools查询MySQL并将结果填充到TextField控件,编写了如下代码。在PowerShell中单独测试Get-Sistema函数时能返回正确值,但点击按钮后无法将结果填充到TextField2中;使用返回单个字符串的函数测试该控件则可正常工作,因此我怀疑问题出在PowerShell的返回类型上。
代码示例
Import-Module Microsoft.PowerShell.ConsoleGuiTools $module = (Get-Module Microsoft.PowerShell.ConsoleGuiTools -List).ModuleBase Add-Type -Path (Join-path $module Terminal.Gui.dll) [void][system.reflection.Assembly]::LoadFrom("C:\Program Files (x86)\MySQL\MySQL Connector Net 8.3.0\MySql.Data.dll") function Get-Sistema { param([string]$Id) $Mysqlhost= "localhost" $Mysqluser= "user" $Mysqlpass= "pw" $Mysqldatabase= "db" $Connection = [MySql.Data.MySqlClient.MySqlConnection]@{ConnectionString="server=$Mysqlhost;uid=$Mysqluser;pwd=$Mysqlpass;database=$Mysqldatabase"} $Connection.Open() $sql = New-Object MySql.Data.MySqlClient.MySqlCommand $sql.Connection = $Connection $sql.CommandText = "SELECT nome_sistema FROM sga_sistemas WHERE ID = $Id" $myreader = $sql.ExecuteReader() while($myreader.Read()){ $myreader.GetString(0) } $myreader.Close() } [Terminal.Gui.Application]::Init() $Window = [Terminal.Gui.Window]::new() $Window.Title = "SGA" $Lb1 = [Terminal.Gui.Label]::New() $Lb1.Text = "OBJETO:" $Lb1.Width = 10 $Lb1.Height = 1 $Lb1.Y = 0 $Window.Add($Lb1) $Field1 = [Terminal.Gui.Textfield]::New() $Field1.Width = 20 $Field1.X = [Terminal.Gui.Pos]::Right($Lb1) $Field1.Y = 0 $Window.Add($Field1) $Field2 = [Terminal.Gui.TextField]::New() $Field2.Width = 20 $Field2.Y = 1 $Window.Add($Field2) $Button = [Terminal.Gui.Button]::New() $Button.Text = "_Consultar" $Button.add_Clicked({ $Field2.Text = Get-Sistema -Id [string]$Field1.Text }) $Button.X = [Terminal.Gui.Pos]::Right($Field1) + 1 $Button.Y = 0 $Window.Add($Button) [Terminal.Gui.Application]::Top.Add($Window) [Terminal.Gui.Application]::Run() [Terminal.Gui.Application]::Shutdown()
测试截图

内容的提问来源于stack exchange,提问作者David Borges
相关产品推荐
相关产品推荐

