在INSERT语句之后无法返回最后一个已知ID

时间:2015-09-03 08:18:46

标签: mysql powershell mysql-insert-id

我试图在使用PowerShell运行MySQL INSERT语句后返回最后插入的ID。我的INSERT工作正常,数据按预期插入数据库。我遇到的问题是抓取刚刚插入的那行的ID。

我的代码如下:

./MySQL.ps1 -Query "insert into table (field1,field2,field3,field4) values ('$val1','$val2','$val3','$val4')"
$last_id = ./MySQL.ps1 -Query "SELECT LAST_INSERT_ID()"
Write-Host "Last ID: $last_id"

返回:

Last ID: System.Data.DataRow

MySQL.ps1

Param(
  [Parameter(
    Mandatory = $true,
    ParameterSetName = '',
    ValueFromPipeline = $true)]
  [string]$Query
)

$MySQLAdminUserName = 'root'
$MySQLAdminPassword = 'password'
$MySQLDatabase = 'storage_manager'
$MySQLHost = 'localhost'
$ConnectionString = "server=" + $MySQLHost + ";port=3306;uid=" +
                    $MySQLAdminUserName + ";pwd=" + $MySQLAdminPassword +
                    ";database=" + $MySQLDatabase

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]
} catch {
  Write-Host "ERROR : Unable to run query : $query `n$Error[0]"
} finally {
  $Connection.Close()
}

我也试过以下内容并获得相同的信息。

SELECT max(id) FROM mytab WHERE category = 1

1 个答案:

答案 0 :(得分:0)

您的函数返回一个DataTable对象,而不仅仅是一个值。要获取所需的值,需要通过字段名称(在您的情况下为SQL函数的名称)选择它:

$result  = ./MySQL.ps1 -Query "SELECT LAST_INSERT_ID()"
$last_id = $result.'LAST_INSERT_ID()'
Write-Host "Last ID: $last_id"

第二行中LAST_INSERT_CD()周围的引号是必需的,因为属性的名称包括括号,并且没有引号PowerShell会将LAST_INSERT_ID()解释为方法而不是属性。您可以通过指定不带括号(或其他特殊字符)的别名来避免引号:

$result  = ./MySQL.ps1 -Query "SELECT LAST_INSERT_ID() AS foo"
$last_id = $result.foo
Write-Host "Last ID: $last_id"