4

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 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That fixed it. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.