问题
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
, theEndEdit
method is implicitly called to end any edits. If theRowState
of the row wasAdded
orModified
, theRowState
becomesUnchanged
. If theRowState
wasDeleted
, the row is removed.
来源:https://stackoverflow.com/questions/47468238/use-sqldataadapter-and-datatable-to-get-and-update-on-sql-server-with-powershell