Powershell – 将API的JSON结果导入SQL Server表中

huangapple go评论61阅读模式
英文:

Powershell - Ingesting API json results into SQL Server table

问题

从 API 端点检索数据并将其插入 SQL Server 中时需要一些帮助。此端点返回 JSON 数据。

我正在简化脚本以提高可读性。脚本获取了我请求的数据,问题出在插入 SQL 表格的部分。

# 使用从 id + secret 计算得出的 payload 传递 'Authorization' 标头值
$Time = Invoke-RestMethod -Uri $TimeCardURL -Method Get -Header @{ Authorization = "Bearer ${AuthorizationValue}" } -Body $Body -Certificate $Cert -ContentType 'application/json'

$Time.teamTimeCards | Select-Object associateOID,timeCards

# SQL 身份验证和插入 $Result 数据
$serverName = "sql-server"
$databaseName = "database"
$tableName = "table"
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "server='$serverName';database='$databaseName';trusted_connection=true;"
$Connection.Open()
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
foreach($ID in $associateOID){
    $insertquery="
        INSERT INTO $tableName
            ([associateOID],[timeCards])
        VALUES
            ('$associateOID','$timeCards')"
    $Command.CommandText = $insertquery
    $Command.ExecuteNonQuery()
}
$Connection.Close();

脚本试图将整个对象 `$associateOID` 加载到列中,导致出现 `“String or binary data would be truncated in table 'database.table', column 'associateOID'. Truncated value: '1 2 3 4 5 6 7 8'. The statement has been terminated.”` 错误。

我猜想脚本中的这一部分存在问题

$Time.teamTimeCards | Select-Object associateOID,timeCards

编辑:问题在于我需要在 `foreach` 语句的内部声明值。

这是我的脚本:

foreach($ID in $associateOID){
    $insertquery="
        INSERT INTO $tableName
            ([associateOID],[timeCards])
        VALUES
            ('$associateOID','$timeCards')"
    $Command.CommandText = $insertquery
    $Command.ExecuteNonQuery()
}

这是修复的部分,稍作调整。感谢 siggemannen 的帮助:

foreach($record in $Time.teamTimeCards){
    $aOID = $record.associateOID
    $timeCards = $record.timeCards | ConvertTo-Json -Compress -Depth 100
    $insertquery="
        INSERT INTO $tableName
            ([associateOID], [timeCards])
        VALUES
            ('$aoid', '$timeCards')"
    $Command.CommandText = $insertquery
    $Command.ExecuteNonQuery()
}
英文:

Looking for some help with ingesting data retrieved from an API endpoint and inserting it into SQL Server. This endpoint returns json.

I'm trimming the script to make this more readable. The script gets the data I'm requesting, the issues is the insert into the SQL table.

# Pass the `Authorization` header value with the payload we calculate from the id + secret
$Time = Invoke-RestMethod -Uri $TimeCardURL -Method Get -Header @{ Authorization = "Bearer ${AuthorizationValue}" } -Body $Body -Certificate $Cert -ContentType 'application/json'


$Time.teamTimeCards | Select-Object associateOID,timeCards

#SQL authentication and insert $Result data 
$serverName = "sql-server"
$databaseName = "database"
$tableName = "table"
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "server='$serverName';database='$databaseName';trusted_connection=true;"
$Connection.Open()
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
foreach($ID in $associateOID){
$insertquery="
  INSERT INTO $tableName
      ([associateOID],[timeCards])
    VALUES
      ('$associateOID','$timeCards')"
  $Command.CommandText = $insertquery
  $Command.ExecuteNonQuery()
}
$Connection.Close();

It's trying to load the entire object $associateOID into the column, which is resulting in a "String or binary data would be truncated in table 'database.table', column 'associateOID'. Truncated value: '1 2 3 4 5 6 7 8'. The statement has been terminated."

I'm guessing there is an issue with this section of the script

$Time.teamTimeCards | Select-Object associateOID,timeCards

EDIT: The issue was I needed to declare the values inside the foreach statement

This is what I had

foreach($ID in $associateOID){
$insertquery="
  INSERT INTO $tableName
      ([associateOID],[timeCards])
    VALUES
      ('$associateOID','$timeCards')"
  $Command.CommandText = $insertquery
  $Command.ExecuteNonQuery()
}

This is what fixed it with a little more massaging. Thanks siggemannen for your help

foreach($record in $Time.teamTimeCards){
  $aOID = $record.associateOID
  $timeCards = $record.timeCards | ConvertTo-Json -Compress -Depth 100
$insertquery="
  INSERT INTO $tableName
      ([associateOID], [timeCards])
    VALUES
      ('$aoid', '$timeCards')"
  $Command.CommandText = $insertquery
  $Command.ExecuteNonQuery()
}

答案1

得分: 1

我重新编写了你的代码以使用另一个数据源,但你可能明白我的意思:


$output = Get-Process | Select-Object Handles, Id, ProcessName
echo($output)

foreach($value in $output){
$id = $value.Id
$name = $value.ProcessName
$insertquery="
  INSERT INTO $tableName
      ([ID],[Name])
    VALUES
      ('$id','$name')"
  echo($insertquery)
  
}
英文:

I rewrote your code to use another source of data, but you probably get the idea:


$output = Get-Process | Select-Object Handles, Id, ProcessName
echo($output)

foreach($value in $output){
$id = $value.Id
$name = $value.ProcessName
$insertquery="
  INSERT INTO $tableName
      ([ID],[Name])
    VALUES
      ('$id','$name')"
  echo($insertquery)
  
}

huangapple
  • 本文由 发表于 2023年2月18日 01:53:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/75487712.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定