查询MySQL数据库

时间:2016-03-28 10:25:58

标签: mysql powershell

$Query1 = "INSERT INTO answers (gid,Key1,key2,key3,key4,key5) VALUES ($gid,'$key1','$key2','$key3','$key4','$key5');"

function Invoke-MySql {
  param($Query)

  $MySQLAdminUserName = 'root'
  $MySQLAdminPassword = <password>
  $MySQLDatabase = <username>
  $MySQLHost = 'localhost'
  $ConnectionString = "server=" + $MySQLHost + ";port=3306;uid=" +
                      $MySQLAdminUserName + ";pwd=" + $MySQLAdminPassword +
                      ";database=" + $MySQLDatabase
  Write-Log "Trying to connect MySql" 0

  try {
    [void][System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")
    $Connection = New-Object MySql.Data.MySqlClient.MySqlConnection
    $Connection.ConnectionString = $ConnectionString
    $Connection.Open()


    $Command = New-Object MySql.Data.MySqlClient.MySqlCommand($Query, $Connection)
    $DataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($Command)
    $DataSet = New-Object System.Data.DataSet
    $RecordCount = $dataAdapter.Fill($dataSet, "data")
    $DataSet.Tables[0] | ft -AutoSize
    Write-Log "Querying the table with following query: $Query" 0
  } catch {
    Write-Log "ERROR : Unable to run query : $query `n$Error[0]" 2
  } finally {
    $Connection.Close()
    Write-Log "MySql connection closed" 0
  }
}

$Result1 = Invoke-MySql -Query $Query1

输出:

PS D:\MYSQL> D:\MYSQL\MySql_Insert&Query.ps1

   gid key1      key2    key3    key4  key5
   --- ----      ----    ----    ----  ----
 31657 c1        c2      c3      c4    c5
 31667 b1        b2      b3      b4    b5
112322 aa        bb      cc      dd    ee
212322 aa        bb      cc      dd    ee
212982 aa        bb      cc      dd    ee
215982 aa        bb      cc      dd    ee
215987 aa        bb      cc      dd    ee
315987 aa        bb      cc      dd    ee

所以这是输出。我从MySQL中获取了结果,但现在我想过滤结果,比如我只想获取一个值,例如gid = 2122322的key3。

1 个答案:

答案 0 :(得分:1)

您的函数返回格式化输出而不是表格本身:

<br />
<b>Warning</b>:  POST Content-Length of 11394639 bytes exceeds the limit of 
8388608 bytes in <b>Unknown </b> on line <b>0</b><br /> []

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

var data = JSON.parse(this.responseText);

删除$DataSet.Tables[0] | ft -AutoSize ,您将能够使用实际的表格数据:

| ft -AutoSize

$Result1 = Invoke-MySql -Query $Query1 | Where-Object { $_.gid -eq 2122322 } | Select-Object -Expand key3 cmdlet用于在向用户显示数据时对其进行格式设置。 从不在需要进一步处理的数据上使用它们(基本上,永远不要在函数中使用它们)。