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

倾然丶 夕夏残阳落幕 提交于 2020-06-12 10:04:09

问题


I am trying to use PowerShell to get a System.Data.DataTable from an SQL server, edit the data, and update it back to the SQL server but I cannot get it to work. The below code runs/executes but the data is not changed.

$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()

回答1:


You should not call AcceptChange on the row, instead you need to call EndEdit.

When call AcceptChanges, it ends edit but marks the row as Unchanged, so it will not be processed by the DataAdapter since it's marked as unchanged.

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.



来源:https://stackoverflow.com/questions/47468238/use-sqldataadapter-and-datatable-to-get-and-update-on-sql-server-with-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!