1
我有对象($itemObjectArray
)的阵列,每一个具有这些特性和像这样的一些值:Powershell的插入物到SQL Server数据库更优雅溶液
ID : 1234
Location : USA
Price : $500
Color : Blue
我有一个SQL Server 2012的表称为Items
列名称与对象属性名称匹配,如下所示:
TABLE Items (
ID
Location
Price
Color
PRIMARY KEY (ID)
)
我创建了以下代码以将对象插入到SQL Server表中。我认为我的代码有点粗俗。有没有更好的方法来做到这一点,因为列名与对象属性名匹配?
$itemObjectArray | %{ #step through array
#get property names, which match column names
$names = $_ | Get-Member -membertype properties
Foreach($name in $names.name){ #make SQL string for column names
$cols += $name + ","
}
$cols = $cols.trimend(",") #get rid of last comma
Foreach($name in $names.name){
#step through properties, get values and build values string
$vals += "'" + $_.$($name) + "',"
}
$vals = $vals.trimend(",") #get rid of last comma
$sqlCommand.CommandText = "INSERT INTO Items ($cols) VALUES ($vals)"
$sqlCommand.ExecuteNonQuery() #insert
$cols = $Null #wipe
$vals = $Null
}
这可能会在CodeReview网站上收到更多反馈。 StackOverflow是用于帮助编程问题(我的代码错误,我不确定如何解决它) – user4317867
我会使用类似[this](https://gallery.technet.microsoft.com/scriptcenter/Import-Large-CSVs -INTO-SQL 216223d9)。 –