sql-serverpowershelldatatablesqldataadapter

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


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

Solution

  • 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.