使用 SqlDataAdapter 和 DataTable 通过 PowerShell 在 SQL 服务器上获取和更新

Use SqlDataAdapter and DataTable to get and update on SQL server with PowerShell

我正在尝试使用 PowerShell 从 SQL 服务器获取 System.Data.DataTable,编辑数据,并将其更新回 SQL 服务器,但我无法获取它工作。下面的代码 runs/executes 但数据没有改变。

$sqlConnection = new-object System.Data.SqlClient.SqlConnection("Server=server,1234; Database=dingo; Trusted_Connection=True;")
$sqlConnection.open()

$sqlCommand = $sqlConnection.CreateCommand()
$sqlCommand.CommandText = "SELECT * FROM dbo.test"

$dt = new-object System.Data.DataTable
$adapter = new-object System.Data.SqlClient.SqlDataAdapter($sqlCommand)

$adapter.Fill($dt)

# edit the rows
$dt.Rows[0].BeginEdit()
$dt.Rows[0]["a"] = "nacho"
$dt.Rows[0].AcceptChanges()

# command builder
$cb = new-object system.data.sqlclient.sqlcommandbuilder($adapter)

$adapter.UpdateCommand = $cb.GetUpdateCommand()


$adapter.Update($dt)

$sqlConnection.Close()

你不应该打电话给 AcceptChange on the row, instead you need to call EndEdit

当调用 AcceptChanges 时,它结束编辑但将行标记为 Unchanged,因此它不会被 DataAdapter 处理,因为它被标记为未更改。

When invoking AcceptChanges, the EndEdit method is implicitly called to end any edits. If the RowState of the row was Added or Modified, the RowState becomes Unchanged. If the RowState was Deleted, the row is removed.