我正在尝试使用带有PowerShell的API填充SQL表。
$conn = New-Object System.Data.SqlClient.SqlConnection("Data Source=SERVERNAME; Initial Catalog=DATABASENAME; Integrated Security=SSPI")
$conn.open()
$cmd = $conn.CreateCommand()
$request = 'http://data.website.com/api/'
If ($JSONResult.success){
$JSONResult.rates.PSObject.Properties | ForEach-Object {
New-Object -Type PSObject -Property @{
'date' = $JSONResult.date
'timestamp' = $JSONResult.timestamp
'base' = $JSONResult.base
'currency' = $_.name
'rate' = $_.value
}
} | select date,timestamp,base,currency,rate|ft -auto
}
foreach($obj in $JSONResult) {
$cmd.CommandText = "INSERT ExRate VALUES (@Date, @Timestamp, @Base, @Currency, @Rate)"
$cmd.Parameters.Add("@Date", $obj.date);
$cmd.Parameters.Add("@Timestam", $obj.timestamp);
$cmd.Parameters.Add("@Base", $obj.base);
$cmd.Parameters.Add("@Currency", $obj.currency);
$cmd.Parameters.Add("@Rate", $obj.rate);
$cmd.ExecuteNonQuery()
$cmd.Parameters.clear();
}
$conn.Close()
这是我得到的错误:
使用“ 0”参数调用“ ExecuteNonQuery”的异常:“参数化查询'(@Date nvarchar(10),@ Timestamp int,@ Base nvarchar(3),@ Currency n'期望参数'@未提供货币”。
答案 0 :(得分:0)
我相信这是您想要的,我将rates.psobject.Properties传递到了foreach:
$j = '{ "success": true, "timestamp": 1519296206, "base": "EUR", "date": "2018-06-20", "rates": { "AUD": 1.566015, "CAD": 1.560132, "CHF": 1.154727, "CNY": 7.827874, "GBP": 0.882047, "JPY": 132.360679, "USD": 1.23396 } } '
$j2 = $J |convertfrom-json
$results = $j2.rates.psobject.Properties | foreach {
New-Object -Type PSObject -Property @{
'date' = $($j2.date)
'timestamp' = $($j2.timestamp)
'base' = $($j2.base )
'currency' = $_.name
'rate' = $_.value
}
}
结果如下:
date : 2018-06-20
currency : AUD
timestamp : 1519296206
rate : 1.566015
base : EUR
date : 2018-06-20
currency : CAD
timestamp : 1519296206
rate : 1.560132
base : EUR
date : 2018-06-20
currency : CHF
timestamp : 1519296206
rate : 1.154727
base : EUR
date : 2018-06-20
currency : CNY
timestamp : 1519296206
rate : 7.827874
base : EUR
date : 2018-06-20
currency : GBP
timestamp : 1519296206
rate : 0.882047
base : EUR
date : 2018-06-20
currency : JPY
timestamp : 1519296206
rate : 132.360679
base : EUR
date : 2018-06-20
currency : USD
timestamp : 1519296206
rate : 1.23396
base : EUR
其余代码
foreach($obj in $results) {
$cmd.CommandText = "INSERT ExRate VALUES (@Date, @Timestamp, @Base, @Currency, @Rate)"
$cmd.Parameters.Add("@Date", $obj.date);
$cmd.Parameters.Add("@Timestamp", $obj.timestamp);
$cmd.Parameters.Add("@Base", $obj.base);
$cmd.Parameters.Add("@Currency", $obj.currency);
$cmd.Parameters.Add("@Rate", $obj.rate);
$cmd.ExecuteNonQuery()
$cmd.Parameters.clear();
}
$conn.Close()