0

How trying to figure out how to use SqlDataAdapter.Update(DataTable) method using a parameterised query. How can I add the values to the command without iterating over the whole DataTable?

And how can I execute the SqlDataAdapter insert and update methods within a transaction?

What I have so far is the following:

internal void InsertUpdate(DataTable dt){
    using(var con = new SqlConnection(ConnectionString)){
         var sb = new StringBuilder();
         sb.AppendLine("UPDATE myTable");
         sb.AppendLine("SET prop1 = @p1, prop2 = qp2");
         sb.AppendLine("WHERE id = @id");
         var cmd = new SqlCommand(sb.ToString());
         cmd.Parameters.AddWithValue("p1", ????);
         cmd.Parameters.AddWithValue("p2", ????);
         cmd.Parameters.AddWithValue("id", ????);
         var adapter = new SqlDataAdapter(selectQuery, con);
         adapter.UpdateCommand = cmd;
         adapter.Update(dt);
    }
}

Best Regards

Jay

1 Answer 1

1

Instead of using Parameters.AddWithValue(...), use Parameters.Add(new SqlParameter(...)) and use one of the last three constructors for SqlParameter documents here: SqlParameter Class MSDN documentation. They allow you to specify a column which will be used at runtime to fill the parameter. For example, here is a line from one of my current programs:

UpdateCommand.Parameters.Add(new OleDbParameter("FK_CustomerID", global::System.Data.OleDb.OleDbType.Integer, 0, global::System.Data.ParameterDirection.Input, ((byte)(0)), ((byte)(0)), "FK_CustomerID", global::System.Data.DataRowVersion.Current, false, null));

Note the second use of "FK_CustomerID", which indicates to use this DataTable column for the parameter.

Regarding using transactions, take a look at this for some ideas: Transactions with TableAdapters, a lazy man's approach. Regards, Drew

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

Comments

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.